1

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

Jesper

1

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.

1

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();
0

I got this working, with objectmanager.

Is there a better way to do it?

<?php 
$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
0

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.