简体   繁体   中英

How can I insert a dynamic menu item in a specific place?

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

Quick and Dirty Solution:

在此处输入图片说明

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM