2

I am trying to get a custom attribute value within my phtml file but struggling to get this to work? getData() & getCustomAttribute() doesn't seem to work. I believe this is because I am using the Magento\Catalog\Block\Navigation class to loop through my categories?

Can anyone advise how I can get my custom attribute value within my loop in my product-categories.phtml?

default.xml within my theme

<block class="Magento\Catalog\Block\Navigation" name="product.categories" template="Magento_Theme::html/product-categories.phtml"></block>

product-categories.phtml

<?php
if (!$block->getCategory()) {
    return;
}
$_categories = $block->getCategory()->getChildrenCategories();
$_count = is_array($_categories) ? count($_categories) : $_categories->count();
if ($_count) {
    ?>
    <ul class="list-quicklinks row med-gutter">
        <?php 
        foreach ($_categories as $_category) {
            if ($_category->getIsActive()) {
                ?>
                <li>
                    <a href="<?php /* @escapeNotVerified */ echo $block->getCategoryUrl($_category) ?>" title="<?php echo $block->escapeHtml($_category->getName()) ?>"><?php echo $block->escapeHtml($_category->getName()) ?></a>
                    <?php
                    //$short_description = $_category->getData('short_category_description');
                    //$short_description = $_category->getCustomAttribute('short_category_description');
                    //$short_description = $this->helper('Magento\Catalog\Helper\Output')->categoryAttribute($_category, '', 'short_category_description');
                    ?>
                    <p><?php // echo $short_description; ?></p> 
                </li>
                <?php 
            }
        }
        ?>
    </ul>
    <?php
}
?>

UPDATE:

namespace Autosmart\CategoryAttributes\Model;

class Category extends \Magento\Catalog\Model\Category
{
    public function getShortCategoryDescription()
    {            
        //return "working";  
        return $this->_getAttribute('category_short_description');
    }
}

I've created a modal with custom function getShortCategoryDescription() which I can call by $_category->getShortCategoryDescription() however I am unsure how to get this to return my short description attribute. The above code gives me an error:

1 exception(s):
Exception #0 (Magento\Framework\Exception\LocalizedException): Invalid method Module\CategoryAttributes\Model\Category\Interceptor::_getAttribute
0

In your custom template try this to get the custom attribute value.

 $block->getCategory()->getChildrenCategories()->getAttribute([your_custom_attribute_code_name]);

Hope this will help you.

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.