Update Nav Menu Items Programmatically

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?

0

Leave a Comment