How can I create a link on "product page" to the "category page" a product is assigned?



A product can be assigned to many categories so this can a challenge.

Just a quick approach; create a product attribute and assign the necessary information and display it in the theme.


There are no simple answers in Magento but to get the url in a template file heres the 'dirty' way

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$currentCategory = $objectManager->get('Magento\Framework\Registry')->registry('current_category');
echo $currentCategory->getUrl();

I got this working, with objectmanager.

Is there a better way to do it?

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
$categories = $product->getCategoryIds(); /*will return category ids array*/
foreach($categories as $category){
    $cat = $objectManager->create('Magento\Catalog\Model\Category')->load($category);

Se alle <a href="<?php echo $cat->getUrl(); ?>"><?php echo $cat->getName(); ?></a>
  • this code loops through all assigned categories and adds a link to the last category the current product is assigned to not the category the user came from before they arrived on the product page (as per the question). – bjornredemption Jan 3 at 14:31

Using Current Category :-

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');

  <a href="<?php echo $category->getUrl(); ?>"><?php echo $category->getName(); ?></a>

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.