2

I know this may sound stupid, but I created a code which (in theory) should add a few submenus to my primary menu.

However I don't seem to be able to display this new menu because I don't know when I should execute it in my theme.

My question therefore: Where do I place wp_update_nav_menu_items(...)?

 

 

My Code:

$c = array(
    "taxonomy" => $post->post_name,
    "hide_empty" => false,
    "orderby" => "term_id"
);
$categories = get_categories( $c );

if (count($categories) != 0) {
    $theme_location = 'primary';
    $theme_locations = get_nav_menu_locations();
    $menu_obj = get_term( $theme_locations[$theme_location], 'nav_menu' );
    $menu_name = $menu_obj->name;
    $menu_id = $menu_obj->term_id;

    $menu = wp_get_nav_menu_items( $menu_id );
    foreach($menu as $menu_item) {
        if ($menu_item->object_id == $post->ID) {
            $post_menu = $menu_item->db_id;
        }
    }

    foreach( $categories as $cat ) {
        add_cat($cat);
    }

    function add_cat($cat) {
        $item = array(
            'menu-item-title' => $cat->name,
            'menu-item-parent-id' => $post_menu,
            'menu-item-url' => $cat->slug,
            'menu-item-status' => 'publish'
        );
        $sub_id = wp_update_nav_menu_item( $menu_id, 0, $item );
    }
}

As far as I know, this should add all categories from the taxonomy with the same slug as this post as sub-item. Right?

3
  • 1
    Instead of creating program that adds all categories at once, try hooking to an action like create_{$taxonomy} and add a new menu item every time a new term is created.
    – Z. Zlatev
    Commented Aug 29, 2017 at 12:25
  • @Zlatev It should only display these submenus on this specific page...
    – Consti P
    Commented Aug 29, 2017 at 12:27
  • 1
    Then don't change the whole menu for that single page. Instead hook to wp_nav_menu_objects and add your submenu items on the fly.
    – Z. Zlatev
    Commented Aug 29, 2017 at 12:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.