0

Magento2 How to show categories of product when product is opened from search bar? i want to load all parent categories id of product that i want to open from direct search bar not from menu.

7
  • by default when i opened any product from search bar it not save its parent categories ids i want to save its all category ids when i opened product from search bar Oct 14, 2019 at 5:48
  • Where do you want these categories? On breadcrumb? Oct 14, 2019 at 5:53
  • yes or its hidden no issue but it get all its parent categories id when i will search product from search bar and opened it. Oct 14, 2019 at 5:54
  • i have to add some filter using product parent categories ids. when product opened from search bar Oct 14, 2019 at 5:57
  • i have get a current category of product now i want to get parent categories of current category Oct 14, 2019 at 6:08

1 Answer 1

0

You can get category collection from current product using this:

$product = $this->registry->registry('current_product');
$categoryCollection = clone $product->getCategoryCollection();

If you are using Magento 2.3+ then registry wont work for you, in that case you need to get current product id by this:

$this->request->getParam('product_id');

where $this->request is the instance of \Magento\Framework\App\RequestInterface. You can load your product by product_id

where $this->registry is a instance of Magento\Framework\Registry

If you want tree level structure for breadcrumb, then you need to understand that product might be attached to multiple categories. So the best way to get proper categories tree is by getting product from highest level, like this:

    $product = $this->registry->registry('current_product');
    $categoryCollection = clone $product->getCategoryCollection();
    $categoryCollection->clear();
    $categoryCollection->addAttributeToSort('level', $categoryCollection::SORT_ORDER_DESC)->addAttributeToFilter('path', array('like' => "1/" . $this->_storeManager->getStore()->getRootCategoryId() . "/%"));
    $categoryCollection->setPageSize(1);
    $currentTree = $categoryCollection->getFirstItem()->getParentCategories();
    foreach ($currentTree as $category) {
        echo $category->getName()."<br>";
        echo $category->getUrl()."<br>";
    }

Hope this will help you

2
  • i want without registry Oct 14, 2019 at 6:56
  • Answer updated, please check Oct 14, 2019 at 7:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.