2

I need to make sure only menu items i.e. categories with the flag Include in Menu set to true to be shown in the main menu.

As far as I understood, using $category->getIncludeInMenu() should do the magic by returning the value. My calls always return Null.

Now I thought: if I can call the method getIncludeInMenu() it should return the right value. Otherwise this method is useless ;-/

Code extracts: Menu.php

protected function getActiveChildren($parent, $level)
{
    $activeChildren = array();
    // --- check level ---
    $maxLevel = $this->getConfig('is_level');
    if(!$maxLevel) $maxLevel = 3;
    if ($maxLevel > 0)
    {
        if ($level >= ($maxLevel - 1)) return $activeChildren;
    }
    $childs = $parent->getChildrenCategories();
    if (count($childs))
    {
        foreach ($childs as $child) 
        {
            if ($child->getIsActive())
            {
                array_push($activeChildren, $child);
            }
        }
    }
    return $activeChildren;
}

When I change if ($child->getIsActive()) to if ($child->getIsActive() && $child->getIncludeInMenu()) all categories are hidden because getIncludeInMenu() return Null all the time...

Any hint appreciated.

4

The problem

The call to getIncludeInMenu returns NULL because the value is not part of the collection.

Basically, you get your child categories by calling getChildrenCategories. The details of that method can be found in Magento\Catalog\Model\ResourceModel\Category.php :

public function getChildrenCategories($category)
{
    $collection = $category->getCollection();
    /* @var $collection \Magento\Catalog\Model\ResourceModel\Category\Collection */
    $collection->addAttributeToSelect(
        'url_key'
    )->addAttributeToSelect(
        'name'
    )->addAttributeToSelect(
        'all_children'
    )->addAttributeToSelect(
        'is_anchor'
    )->addAttributeToFilter(
        'is_active',
        1
    )->addIdFilter(
        $category->getChildren()
    )->setOrder(
        'position',
        \Magento\Framework\DB\Select::SQL_ASC
    )->joinUrlRewrite()->load();

    return $collection;
}

As you can see the include_in_menu attribute is not added to select, thus every category from that collection don't have this attribute that's why the getIncludeInMenu call always returns NULL.

Possible fix

My suggestion to fix that would be to replace the following code:

$childs = $parent->getChildrenCategories();

With:

$childs = $parent->getChildrenCategories();
// Clear the collection
$childs->clear();
// Add the missing attribute to be selected in the collection
$childs->addAttributeToSelect('include_in_menu');
// Reload the collection
$childs->load();

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.