如何将自定义项添加到特定的WordPress菜单项位置

Way*_*yne 3 php wordpress menu

我有一个注册和显示的主菜单,包括4个链接(家庭,关于,新闻,博客).我想在第二和第三个菜单之间添加html(一个徽标),我想知道这是否可行.

这是一个图表:HOME | 关于| 标志| 新闻| 博客

我正在查看钩子wp_nav_menu_items,但我只能在第一个位置或最后一个位置添加自定义项目.

在我使用jQuery添加html之前,但由于DOM必须完全加载,因此徽标最后加载,我试图让徽标首先显示或同时显示页面内容.

小智 17

我这样解决了类似的问题:

add_filter('wp_nav_menu_items','add_custom_in_menu', 10, 2);

function add_custom_in_menu( $items, $args ) 
{
    if( $args->theme_location == 'primary' ) // only for primary menu
    {
        $items_array = array();
        while ( false !== ( $item_pos = strpos ( $items, '<li', 3 ) ) )
        {
            $items_array[] = substr($items, 0, $item_pos);
            $items = substr($items, $item_pos);
        }
        $items_array[] = $items;
        array_splice($items_array, 2, 0, '<li>custom HTML here</li>'); // insert custom item after 2nd one

        $items = implode('', $items_array);
    }
    return $items;
}
Run Code Online (Sandbox Code Playgroud)

请注意,它仅适用于单级菜单.


Mat*_*ijs 5

Compass 的解决方案几乎没有变化,摆脱了循环。

add_filter('wp_nav_menu_items','add_custom_in_menu', 10, 2);

// add in Logo in the middle of the menu
//
function add_custom_in_menu( $items, $args )
{
    if( $args->theme_location == 'footer_navigation' )
    {
        $new_item       = array( '<li class="menu-logo"><a href="/"><img src="' . get_template_directory_uri() . '/assets/img/logo.png" alt=""></a></li>' );
        $items          = preg_replace( '/<\/li>\s<li/', '</li>,<li',  $items );

        $array_items    = explode( ',', $items );
        array_splice( $array_items, 2, 0, $new_item ); // splice in at position 3
        $items          = implode( '', $array_items );
    }
    return $items;
}
Run Code Online (Sandbox Code Playgroud)

不确定使用内置函数是否会快得多。你的选择