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);
}
}
}
Best Answer
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.