Add items to a menu dynamically

I’m doing a site in WP with dynamic and static content. I’d create the menu from the admin panel. I have 5 sections (Home, about, Boats, News(blog), contact). I’d create a custom post type with new taxonomies for the boats. What I want to do now is, display every new boat model as a sub menu of boats automatically. How can I do that?

Related posts

Leave a Reply

2 comments

  1. You could achieve this with a custom walker function, on your menu. a very simple example:

    class Walker_WPA82563_Submenu extends Walker_Nav_Menu {
        function end_el(&$output, $item, $depth=0, $args=array()) {
            if( 'Boats' == $item->title ){
                $output .= '<ul><li>Dynamic Subnav</li></ul>';
            }
            $output .= "</li>n";  
        }
    }
    

    Then where you call the nav menu, create an instance of your custom walker with the walker argument.

    wp_nav_menu(
        array(
            'theme_location' => 'primary',
            'walker' => new Walker_WPA82563_Submenu
        )
    );
    
  2. I believe there is a much better solution suited for cases when menus are truly dynamic (such as they should change depending on user role, or if there simply are too many combinations of menu items possible which need to be decided on runtime).

    WordPress’ wp_nav_menu_objects hook comes in handiest:

    add_filter('wp_nav_menu_objects', 'addMenuItems', null, 2);
    function addMenuItems($sortedItems, $args)
    {
        $toAdd = [
            (object) [
                'ID'        => 1,               // make sure this doesn't conflict with existing items
                'db_id'     => 1,               // same here
                'title'     => 'To Google!',
                'url'       => 'https://www.google.com',
            ],
        ];
    
        return array_merge($sortedItems, $toAdd);
    }