向WordPress菜单链接添加说明

时间:2018-03-05 01:00:19

标签: wordpress

这是我添加到functions.php文件中的代码。它允许我在菜单链接中添加描述。但是如何在a-tag之外得到跨度,而不包含在其中呢?

// DESCRIPTIONS IN NAV MENU
function nav_menu_description( $item_output, $item, $depth, $args ) {
    if ( !empty( $item->description ) ) {
        $item_output = str_replace( $args->link_after . '</a>', '<span class="menu-item-description">' . $item->description . '</span>' . $args->link_after . '</a>', $item_output );
    }

    return $item_output;
}
add_filter( 'walker_nav_menu_start_el', 'nav_menu_description', 10, 4 );
?>

1 个答案:

答案 0 :(得分:0)

Walker类扩展了WordPress中的现有类。它基本上只是添加一行代码来显示菜单项描述。在主题的functions.php文件中添加此代码。

class Menu_With_Description extends Walker_Nav_Menu {
    function start_el(&$output, $item, $depth, $args) {
        global $wp_query;
        $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

        $class_names = $value = '';

        $classes = empty( $item->classes ) ? array() : (array) $item->classes;

        $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
        $class_names = ' class="' . esc_attr( $class_names ) . '"';

        $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';

        $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
        $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
        $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
        $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';

        $item_output = $args->before;
        $item_output .= '<a'. $attributes .'>';
        $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
        $item_output .= '</a>';
        $item_output .= '<br /><span class="sub">' . $item->description . '</span>';
        $item_output .= $args->after;

        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }
}

WordPress主题使用wp_nav_menu()函数来显示菜单。大多数WordPress主题在header.php模板中添加菜单。但是,您的主题可能已使用其他模板文件来显示菜单。 我们现在需要做的是在你的主题中找到wp_nav_menu()函数(最有可能在header.php中),然后像这样改变它。

<?php $walker = new Menu_With_Description; ?>

<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu', 'walker' => $walker ) ); ?>