0

I'm using Magento 2, I want to display the category name of the product on the product page.

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

// @codingStandardsIgnoreFile

/**
 * Product view template
 *
 * @var $block \Magento\Catalog\Block\Product\View
 */
?>
<?php 
   $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
   //echo $category->getId();
   echo $category->getname();
?>
<?php $_helper = $this->helper('Magento\Catalog\Helper\Output'); ?>
<?php $_product = $block->getProduct(); ?>
<div><span><?php echo $category->getId();?></span></div>
<div class="product-add-form">
    <form action="<?php /* @escapeNotVerified */ echo $block->getSubmitUrl($_product) ?>" method="post"
          id="product_addtocart_form"<?php if ($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
        <input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $_product->getId() ?>" />
        <input type="hidden" name="selected_configurable_option" value="" />
        <input type="hidden" name="related_product" id="related-products-field" value="" />
        <?php echo $block->getBlockHtml('formkey')?>
        <?php echo $block->getChildHtml('form_top'); ?>
        <?php if (!$block->hasOptions()):?>
            <?php echo $block->getChildHtml('product_info_form_content'); ?>
        <?php else:?>
            <?php if ($_product->isSaleable() && $block->getOptionsContainer() == 'container1'):?>
                <?php echo $block->getChildChildHtml('options_container') ?>
            <?php endif;?>
        <?php endif; ?>

        <?php if ($_product->isSaleable() && $block->hasOptions() && $block->getOptionsContainer() == 'container2'):?>
            <?php echo $block->getChildChildHtml('options_container') ?>
        <?php endif;?>
        <?php echo $block->getChildHtml('form_bottom'); ?>
    </form>
</div>
<script>
    require([
        'jquery',
        'Magento_Catalog/js/price-box'
    ], function($){
        var priceBoxes = $('[data-role=priceBox]');

        priceBoxes = priceBoxes.filter(function(index, elem){
            return !$(elem).find('.price-from').length;
        });

        priceBoxes.priceBox({'priceConfig': <?php /* @escapeNotVerified */ echo $block->getJsonConfig() ?>});
    });
</script>
1

Try this at

app/design/frontend/Theme/Package/Magento_Catalog/templates/product/view/form.phtml

<?php 
   $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
    echo $category->getId();
    echo $category->getName();
?>
  • Can you please let me know in which file should I add the above code? Thanks in advance – anirvan Nov 21 '17 at 4:18
  • where you want to display Category name – Magento 2 Nov 21 '17 at 4:19
  • I want to display the Category name above the Product Name in the catalog-view-page – anirvan Nov 21 '17 at 4:20
  • app/design/frontend/Theme/Package/Magento_Catalog/templates/product/view/form.phtml – Magento 2 Nov 21 '17 at 4:22
  • I don't know exact path enable template path hints then you will get exact path – Magento 2 Nov 21 '17 at 4:23
0

You can show current category name using following methods.

Method 1. Using dependency injection

app/code/Vendor/Module/Block/CurrentCategory.php

<?php
namespace Vendor\Module\Block;

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

    protected $_registry;

    public function __construct(
        \Magento\Framework\Registry $registry
    )
    {
        $this->_registry = $registry;
    }

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

}

app/code/Vendor/Module/view/frontend/templates/current_category.phtml

echo $block->getCurrentCategory()->getName();

app/code/Vendor/Module/view/frontend/layout/catalog_product_view.xml

<?xml version="1.0"?>

<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Vendor\Module\Block\CurrentCategory" name="current.category" template="Vendor_Module::current_category.phtml" />
        </referenceContainer>
        <move element="current.category" destination="product.info.main" before="page.main.title"/>
    </body>
</page>

Method 2. Using objectManager

app/design/frontend/vendor/theme/Magento_Catalog/templates/product/view/current_category.phtml

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

echo $current_category->getName();

app/design/frontend/vendor/theme/Magento_Catalog/layout/catalog_product_view.xml

<?xml version="1.0"?>

<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="current.category" template="Magento_Catalog::product/view/current_category.phtml" />
        </referenceContainer>
        <move element="current.category" destination="product.info.main" before="page.main.title"/>
    </body>
</page>
0

There are 2 ways to get category Data:

=> Using Object Manager:

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance(); 
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');
$registry = $objectManager->get('\Magento\Framework\Registry');
$currentCategory = $registry->registry('current_category');
echo $currentCategory->getName() . '<br />';
echo $currentCategory->getUrl() ;

=> Using Block :

1) Create Block:

app/code/Allin/HelloWorld/Block/HelloWorld.php

<?php
namespace Allin\HelloWorld\Block;
class HelloWorld 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 _prepareLayout()
    {
        return parent::_prepareLayout();
    }

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

    public function getCurrentProduct()
    {        
        return $this->_registry->registry('current_product');
    }    

}
?>

2) Get current category in any template (.phtml) file

// print current category data
$currentCategory = $block->getCurrentCategory();
echo $currentCategory->getName() . '<br />';
echo $currentCategory->getUrl() ;
-1
**Add XML Code Theme/namespace/Magento_Catalog/templates/product/view**

<block class="Magento\Catalog\Block\Product\View" name="product.info.category" after="product.price.final" template="product/view/current_category.phtml" />


**Create New File    Theme/namespace/Magento_Catalog/templates/product/view**  

      <?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){

            echo $category->getName();
            }

        ?>
  • Please do not use load() inside foreach loop. – sv3n Nov 30 '18 at 10:34

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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