5

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.

1

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

  • ,this is returning only url of product ,not full path. – akgola Apr 24 at 6:57
  • @akgola what you mean by path .You can't get the path of the product page as html is generated from the magento's structure dynamically – rinzler Apr 24 at 7:52
  • this will generate url like www.example.com/category/product.html – rinzler Apr 24 at 7:54
  • ,I mean in format Home > Women > Dresses > Maxi Dresses not url format. – akgola Apr 24 at 10:11
  • i added new solution @akgola .please check it – rinzler Apr 24 at 13:01
0

sample

here a image where i put path below add to cart button just adding below code in addtocart.phtml in

app/code/vendor_name/extension_Name/view/frontend/templates/product/view/addtocart.phtml
<?php echo $this->getLayout()->getBlock('breadcrumbs')->toHtml(); ?>

add this to any phtml file you will get the path you wanted

hope this helps you

  • one small query i.e what if customer directly redirect from home page to product page? – Nagaraju Kasa Apr 29 at 13:18
  • @NagarajuKasa i didn't understand your question because it was to get the path(breadcrumbs) – rinzler May 1 at 6:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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