1

I have the following code to get all categories which are active but not included in the menu. It then loops around these and updates them to be included in the menu. The script works on the frontend however the issue is when I check a few categories in the admin it still shows as "Include In Menu" as being no.

Is there anything I need to add to my script so that the admin reflects the change? Not sure if its affects anything but I have flat categories enabled

class Index extends \Magento\Backend\App\Action
{
    protected $categoryFactory;
    protected $categoryRepository;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryFactory,
        \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository
    ) {
        $this->categoryFactory = $categoryFactory;
        $this->categoryRepository = $categoryRepository;
        parent::__construct($context);
    }

    public function execute()
    {
        $categories = $this->categoryFactory->create()
            ->addAttributeToFilter('is_active', 1)
            ->addAttributeToFilter('include_in_menu', 0)
            ->addAttributeToSort('id')
            ->addAttributeToSelect('*');

        foreach ($categories as $category) {
            $category->setIncludeInMenu(1);
            $category->setStoreId(1);
            $this->categoryRepository->save($category);
        }

    }
}

2 Answers 2

1

This issue is totally belongs to the store id.

So if you want same data on the frontend and admin you need to set store id is 0.

By default Admin store id = 0, Front End store id = 1 ,

so you need to change this line from $category->setStoreId(1); to => $category->setStoreId(0);

This is not only for category for products too.

enter image description here

0

You can inject the StoreManagerInterface in your constructor and change the default store before updating the category:

public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager
) {
    $this->storeManager = $storeManager;
}

$this->storeManager->setCurrentStore(0);

// Now you can update your category

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.