9

I am trying to get product categories on product detail page.

I tried using

 $categoryIds = $_product->getCategoryIds();

But it is not working for me.

Also i tried

  $categories = $product->getCategoryCollection()->addAttributeToSelect('name');
  foreach($categories as $category)
  { 
     var_dump($category->getName());
  }

This code show me NULL value.

Can you guys help me with this? I am searching for solution from past 2 days. Now its a headache for me.

Thanks in advance.

/************* Edit**********/

I also tried by creating module block. But its not working for me:

Here is my code:

  <?php
            /**
             * Copyright © 2016 Magento. All rights reserved.
             * See COPYING.txt for license details.
             */

            /**
             * Product description block
             *
             * @author     Magento Core Team <[email protected]>
             */
            namespace Magento\Catalog\Block\Product\View;

            use Magento\Catalog\Model\Product;
            use Magento\Framework\Pricing\PriceCurrencyInterface;


            class ProductsCategory extends \Magento\Framework\View\Element\Template
            {

                protected $_registry;
             /**
                 * @var Product
                 */
                protected $_product;

                /**
                 * Product option
                 *
                 * @var \Magento\Catalog\Model\Product\Option
                 */
                protected $_option;

                /**
                 * Core registry
                 *
                 * @var \Magento\Framework\Registry
                 */
                protected $_registry = null;

                /**
                 * Catalog product
                 *
                 * @var Product
                 */
                protected $_catalogProduct;

                /**
                 * @var \Magento\Framework\Json\EncoderInterface
                 */
                protected $_jsonEncoder;

                /**
                 * @var \Magento\Framework\Pricing\Helper\Data
                 */
                protected $pricingHelper;

                /**
                 * @var \Magento\Catalog\Helper\Data
                 */
                protected $_catalogData;

                /**
                 * @param \Magento\Framework\View\Element\Template\Context $context
                 * @param \Magento\Framework\Pricing\Helper\Data $pricingHelper
                 * @param \Magento\Catalog\Helper\Data $catalogData
                 * @param \Magento\Framework\Json\EncoderInterface $jsonEncoder
                 * @param \Magento\Catalog\Model\Product\Option $option
                 * @param \Magento\Framework\Registry $registry
                 * @param \Magento\Framework\Stdlib\ArrayUtils $arrayUtils
                 * @param array $data
                 */
                public function __construct(
                    \Magento\Framework\View\Element\Template\Context $context,
                    \Magento\Framework\Pricing\Helper\Data $pricingHelper,
                    \Magento\Catalog\Helper\Data $catalogData,
                    \Magento\Framework\Json\EncoderInterface $jsonEncoder,
                    \Magento\Catalog\Model\Product\Option $option,
                    \Magento\Framework\Registry $registry,
                    \Magento\Framework\Stdlib\ArrayUtils $arrayUtils,
                    array $data = []
                ) {
                    echo "coming in coonstructor";
                    $this->pricingHelper = $pricingHelper;
                    $this->_catalogData = $catalogData;
                    $this->_jsonEncoder = $jsonEncoder;
                    $this->_registry = $registry;
                    $this->_option = $option;
                    $this->arrayUtils = $arrayUtils;
                    parent::__construct($context, $data);
                }


                public function getCurrentCategory()
                {
                    return "fhdsfgdsf";
                }

            }

My phtml file:

     <?php //if ($currentCategory = $block->getCurrentCategory()): 
     $currentCategory = $block->getCurrentCategory();
     ?>
    <div>
        <span><?php echo "testing";
        echo $currentCategory; ?></span>
    </div>

Called phtml via xml:

    <referenceContainer name="content">
        <container name="product.info.main" htmlTag="div" htmlClass="product-info-main" before="-">
            <block class="Magento\Catalog\Block\Product\View" name="product.category.name" template="product/view/productscategory.phtml" >
        </block></referenceContainer>
1

2 Answers 2

34

Please use below code :

<?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);
    echo $cat->getName();
    }

?>
7
  • Thanks alot.. It works.. Can you tell me if i want to get name of category then what should i use?
    – Thomas
    Commented Nov 4, 2016 at 8:32
  • please check my answer just edited.
    – user46386
    Commented Nov 4, 2016 at 8:48
  • So we can get the name and thats cool.. but how would i get enough info to build a real product list? (img, description, price, colors, etc...) Commented Aug 14, 2017 at 5:05
  • 1
    @JamesHarrington like this, echo $cat->getDescription(); echo $cat->getImageUrl(); ... try using a var_dump on $cat like thos var_dump($cat) then you can see every attribute it has
    – Joey
    Commented Oct 27, 2017 at 7:41
  • use dependency injection rather than object manager
    – John
    Commented Dec 5, 2018 at 12:00
4

Try this,

Create a custom module like below code.

create a module block file to get current category name.

<?php
namespace Namespace\Modulename\Block;
class Blockname extends \Magento\Framework\View\Element\Template
{
    protected $_registry;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = []
    )
    {
        $this->_registry = $registry;
        parent::__construct($context, $data);
    }


    public function getCurrentCategory()
    {
        return $this->_registry->registry('current_category');
    }

}
?>

create a phtml file with below code

<?php if ($currentCategory = $block->getCurrentCategory()): ?>
    <div class="detail-category-name">
        <?php echo $currentCategory->getName(); ?>
    </div>
<?php endif; ?>

call above phtml file via xml file.

<referenceContainer name="product.info.main">
            <block class="Namespace\Modulename\Block\Blockname" name="product.category.name" template="Magento_Catalog::product/view/yourfilename.phtml" >
            </block>
</referenceContainer>

And finally you can see category name just above product name on product detail page.

1
  • Thanks for your answer. But i already tried this code. I edited my answer with the code which i tried. I created custom module with name ProductsCategory.php and phtml file with name productscategory.phtml.
    – Thomas
    Commented Nov 4, 2016 at 8:19

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.