0

I can place a new menu item to the end of the root level menu items by using this:

function bv_show_book_online_menu_item($items, $args) {
    if(bv_can_book_online()) {
        if($args->theme_location == 'main-menu') {
            $items .= '<li><a href="/book/">Book Online</a></li>';
        }
    }
    return $items;
}
add_filter('wp_nav_menu_items','bv_show_book_online_menu_item', 10, 2);

But how can I actually insert the item in any place I want? I actually want to place it in the middle of submenu like this:

Menu Item
    Submenu Item
    Submenu Item
    <-- Insert new submenu item -->
    Submenu Item
    Submenu Item
Menu Item
    Submenu Item
    Submenu Item
    Submenu Item
etc
Lee
  • 4,187
  • 6
  • 25
  • 71

1 Answers1

1

Quick and Dirty Solution:

enter image description here

Install menu items visibility control plugin; this allows you to conditionally display both menu and sub-menu items via the menu page.

Add your own "my_function" function to functions.php or to your own site functions plugin. The plugin should return TRUE when sub menu is to be displayed.

On the WP Dashboard menu page select the optional sub-menu and add this conditional function_exists("my_function") && my_function() to it's visibility field. Simplistically: don't fall over if my_function can't be found, and only display this sub-menu when my_function returns TRUE.

I assume this plugin has to EVALuate the conditional in the visibility field. In theory this is a slight security risk. However when I checked the plugins many support & reviews (months ago) I couldn't find any raising this as a point of concern.

If this is of concern to you; then alternatively you could find the code you need from the plugin source.

scytale
  • 1,339
  • 1
  • 11
  • 14
  • Thanks for this, I'm working on a way to do it without plugins, and do it core into the theme functions, I'll update this question if it works – Lee Feb 09 '18 at 11:44
  • If you come up with a code solution then myself and others would be interested so add it as an answer and mark it as the right answer. I've a feeling you'll have to use the Walker class - to much fiddling for me (different menu items & sub-links depending on visitor country) hence my use of plugin. I've not checked but code in above plugin may give you some clue how to implement. – scytale Feb 09 '18 at 19:07
  • Actually it doesn’t require a walker. Same idea as the action hook, but uses wp_get_nav_menu_items instead to loop through them, then I just insert the link, or function in my case after the nth menu item. It’s surprisingly simple. – Lee Feb 10 '18 at 21:52