Magento – Magento 2 Get Full Category Path for product

categorymagento2

How to get full category path in Magento 2?

For example

Home > Women > Dresses > Maxi Dresses

I am developing script for Google Shopping Feed and there is a node product_type which is require product category in above format

enter image description here

This node should be in below format:

<g:product_type><![CDATA[Home > Women > Dresses > Maxi Dresses]]></g:product_type>

I have searched on forum but didn't found any solution for Magento 2.

If anyone any idea then please share me.

Best Answer

Try this

public function __construct(
             \Magento\Framework\Registry $registry,
                \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository,
                \Magento\Store\Model\StoreManagerInterface $storeManager

            ) {
        $this->storeManager = $storeManager;
        $this->registry = $registry;
        $this->categoryRepository = $categoryRepository;

    }
public function yourfunctionname(){
    $categoryIds = $product->getCategoryIds();
    if (!$categoryIds) {
        return null;
    }
    $category = $this->categoryRepository->get($categoryIds[0], $this->storeManager->getStore()->getId());
    $this->registry->register('current_category',$category);
    $redirectionUrl = $product->getProductUrl();
 }

the __construct contain the dependencies injection you needed to load model and yourfunctionname have the code to get url using the current product page category to get category url

Related Topic