我想在每个菜单项后添加不同的文本

时间:2014-01-28 作者:Nathan S

我希望我的主导航栏显示菜单项,在每个项的标题下都有对所述菜单的简短描述。

为此,我希望将菜单项的“title”属性注入下面的“after”函数中。不太确定如何执行此操作:

// the main menu
function bones_main_nav() {
    // display the wp3 menu if available
    wp_nav_menu(array(
        \'container\' => false,                           // remove nav container
        \'container_class\' => \'menu clearfix\',           // class of container (should you choose to use it)
        \'menu\' => __( \'The Main Menu\', \'bonestheme\' ),  // nav name
        \'menu_class\' => \'nav top-nav clearfix\',         // adding custom nav class
        \'theme_location\' => \'main-nav\',                 // where it\'s located in the theme
        \'before\' => \'\',                                 // before the menu
        \'after\' => \'\',                                  // after the menu
        \'link_before\' => \'\',                            // before each link
        \'link_after\' => \'\',                             // after each link
        \'depth\' => 0,                                   // limit the depth of the nav
        \'fallback_cb\' => \'bones_main_nav_fallback\'      // fallback function
    ));
} /* end bones main nav */
我还担心这会干扰下拉功能。任何帮助都将不胜感激。

1 个回复
SO网友:fischi

你需要一个Custom Walker 为了这个。

在自定义Walker中,可以定义不同元素的起点,在链接后添加一个范围:

class Walker_With_Title_Menu extends Walker_Nav_Menu  {

    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        $output .= sprintf( "\\n<li><a href=\'%s\'%s>%s</a><span class=\'your-line\'>%s</span></li>\\n",
            $item->url,
            ( $item->object_id === get_the_ID() ) ? \' class="current"\' : \'\',
            $item->title,
            $item->title //additional %s in the span that I added
        );
    }

}
如果你想在那里写些不同的东西,你可以在postmeta 并插入它而不是标题。

请务必致电您的wp_nav_menu 使用新Walker:

wp_nav_menu(array(
    \'container\' => false,                           // remove nav container
    \'container_class\' => \'menu clearfix\',           // class of container (should you choose to use it)
    \'menu\' => __( \'The Main Menu\', \'bonestheme\' ),  // nav name
    \'menu_class\' => \'nav top-nav clearfix\',         // adding custom nav class
    \'theme_location\' => \'main-nav\',                 // where it\'s located in the theme
    \'before\' => \'\',                                 // before the menu
    \'after\' => \'\',                                  // after the menu
    \'link_before\' => \'\',                            // before each link
    \'link_after\' => \'\',                             // after each link
    \'depth\' => 0,                                   // limit the depth of the nav
    \'fallback_cb\' => \'bones_main_nav_fallback\',     // fallback function
    \'walker\'=> new Walker_With_Title_Menu()         // **Using your new walker**
));
你打电话的时候不能这么做wp_nav_menu 直接,因为after 参数不允许变量,它需要字符串。

结束