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.
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.
Magento 2.x provides a way to do that from the Dashboard:
- 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.
But this is tedious work especially considering the website has a "rich" category-tree. Here is an example: Home > Consumabile Auto & Moto > Lubrifianti > Uleiuri Motor > 0W-20
.
The only category that has products here is 0W-20. It makes sense that all the products from 0W-20 should also be in its the parent categories.
Question: What is the programming solution that would do the job, recursively?