Skip to content

Instantly share code, notes, and snippets.

@dieppon
Created January 31, 2020 15:01
Show Gist options
  • Select an option

  • Save dieppon/a79bcdb01a1bc7f2387f3274079fba75 to your computer and use it in GitHub Desktop.

Select an option

Save dieppon/a79bcdb01a1bc7f2387f3274079fba75 to your computer and use it in GitHub Desktop.
Automatically add terms to a menu on Wordpress
<?php
/**
* Display Categories on the Primary menu
*/
add_filter('wp_get_nav_menu_items', function ($items, $menu, $args) {
$primary_menu_id = 47; // the id of the main menu;
$shop_menu_item_id = 1248; // the id of the main item that serves as the parent;
$taxonomy_name = 'product_cat'; // the machine name of the vocavulary you want to use;
if( $menu->term_id != $primary_menu_id ) {
return $items;
}
// don't add child categories in administration of menus
if ( is_admin() ) {
return $items;
}
$terms = get_terms([
'taxonomy' => $taxonomy_name,
'hide_empty' => false,
]);
foreach ( $items as $index => $i ) {
if ( $shop_menu_item_id !== $i->ID ) {
continue;
}
foreach ( $terms as $index2 => $term ) {
if ( $term->slug == 'uncategorized' ) {
continue; // remove the uncategorized term
}
if ( $term->parent != 0 ) {
continue; // remove children as this stage
}
$url = get_term_link( $term );
$e = new \stdClass();
$e->title = $term->name;
$e->url = $url;
$e->menu_order = 100 * ( $term->term_order + 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;
$term_children = get_term_children( $term->term_id, $taxonomy_name );
// add child categories
foreach ( $term_children as $index3 => $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 = 200 * ( $child->term_order + 1 ) + $index3;
$e->post_type = 'nav_menu_item';
$e->post_status = 'published';
$e->post_parent = $term->ID;
$e->menu_item_parent = $term->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