Based on Sort WooCommerce product category sub menu items by name ASC in WordPress menu answer code to my previous question, I am able to automatically display child subcategories as menu sub items for some product categories in my WordPress navigation menu.
My question is: Is it possible to hide empty subcategories (sub menu items)?
And maybe if possible hide categories that contains only one product that is Sold Out.
2
Answers
You can use get_terms() , here you can specify more options, so
Will become
This also has a ‘order_by’ parameter, that defaults to the name of a term
You can use additionally
get_terms()
with the following parameters:'include'
to include all child terms fromget_term_children()
function as a coma separated string of term ids.'orderby'
with'name'
attribute to sort terms by name,'order'
with ‘ASC’ attribute to sort terms ascending,'hide_empty'
withtrue
attribute to not include empty terms.So sorting will be made directly without requiring a foreach loop and you will get also directly an array of WP_Term objects.
The revisited code:
Code goes in functions.php file of the active child theme (or active theme). Tested and works.