Breadcrumbs for products Drupal Commerce 2

When using various topics supporting the Drupal Commerce module, you can encounter the problem of the absence of sanely working breadcrumbs. Unfortunately, not every module supports commerce product, so I will provide a small fragment of code below, which will help display breadcrumbs on the product page, using a custom module, which once already laid out on our resource.

This is just a small fragment of the code that will allow you to understand how to get variable product of the commerce, for further processing and output in breadcrumbs.

if ($path_args[1] == 'product') {
            $pid = $path_args[2];
            $entity_manager = \Drupal::entityTypeManager();
            $product = \Drupal\commerce_product\Entity\Product::load($pid);
            if ($product->type->getString() == 'default') {
                $display = TRUE;
                if (!$product->field_category->isEmpty()) {
                    $category_id = $product->field_category[0]->target_id;
                    $category = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($category_id);
                    $aliasManager = \Drupal::service('path_alias.manager');
                    $category_url = $aliasManager->getAliasByPath('/taxonomy/term/' . $category_id);
                    $category_title = $category->name->value;
                    $category_parent_id = $category->parent->target_id;
                    if ($category_parent_id !== '0') {
                        $category_parent = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($category_parent_id);
                        $category_parent_url = $aliasManager->getAliasByPath('/taxonomy/term/' . $category_parent_id);
                        $category_parent_title = $category_parent->name->value;
                        $breaðÊÉíU  ðÊÉíU                  ЛÉÉíU           ™ÉÉíU  XÊÉíU          ÊÉíU   @      ÊÉíU          sp;   'url' => $category_parent_url,
                            'name' => $category_parent_title,
                            'position' => $position,
                        ];
                        $position++;
                    }
                    $breadcrumbs[] = [
                        'url' => $category_url,
                        'name' => $category_title,
                        'position' => $position,
                    ];
                }
            }
            $breadcrumbs[]['name'] = $product->title->value;
        }

In this example, we will derive the term of taxonomy in bread crumbs, tied to the product, its parental term, if any, and the name of the product itself.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
The comment language code.