Magento 2.1 – Assign Products to Ancestor Categories Programmatically

categorycategory-productsmagento-2.1magento2

I am working on a Magento 2.1.7 shop and I have created a child-theme of Magento Blank

The products are organized into categories and subcategories. In other words, they are organized into parent categories and children categories.

Whenever a product is assigned, through the Magento admin, to a child category, I want it to be automatically assigned to all the ancestor categories of that child category.

The Footwear category tree

I want to manually assign all the boot brands in the store to the "Boots" child category add I want all boots to be automatically put, by Magento, in the "Footwear" parent category.

Question: What is the programming solution that would do the job, recursively?

Best Answer

There is a simple solution which Magento 2.x provides by default.

  • Go to Products > Categories.
  • Click on the (parent) category in which you want to show the products of the sub-category.
  • Under Display Settings, set Yes for Anchor field.
  • Save the category, flush Magento's cache and reindex.

Please let me know if the solution works for you.