Skip to content

Instantly share code, notes, and snippets.

@ncesar
Created January 24, 2019 13:14
Show Gist options
  • Save ncesar/c7713bdd25639aff00f2fea03bc90dcc to your computer and use it in GitHub Desktop.
Save ncesar/c7713bdd25639aff00f2fea03bc90dcc to your computer and use it in GitHub Desktop.
Auto add WooCommerce categories children in a wordpress menu
add_filter("wp_get_nav_menu_items", function ($items, $menu, $args) {
if( $menu->term_id != 111 ) return $items ;
// don't add child categories in administration of menus
if (is_admin()) {
return $items;
}
foreach ($items as $index => $i) {
if ("product_cat" !== $i->object) {
continue;
}
$term_children = get_term_children($i->object_id, "product_cat");
// add child categories
foreach ($term_children as $index2 => $child_id) {
$child = get_term($child_id);
if( $child->count == 0 ) continue;
$url = get_term_link($child);
$e = new \stdClass();
$e->title = $child->name;
$e->url = $url;
$e->menu_order = 500 * ($index + 1) + $index2;
$e->post_type = "nav_menu_item";
$e->post_status = "published";
$e->post_parent = $i->ID;
$e->menu_item_parent = $i->ID;
$e->type = "custom";
$e->object = "custom";
$e->description = "";
$e->object_id = 0;
$e->db_id = 0;
$e->ID = 0;
$e->classes = array();
$items[] = $e;
}
}
return $items;
}, 10, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment