在Wordpress中将子项的数量添加到父页面菜单项

时间:2013-08-12 09:13:34

标签: wordpress menu parent menuitem children

我在Wordpress中有一个包含10个父页面的菜单。每个父页面都有很多子页面(子页面)。我想在每个菜单项附加一个数字,显示该项目有多少个孩子。

示例:

标准菜单:产品|投资组合|商店|作业

我想要的菜单:产品(49)|投资组合(14)|商店(22)|乔布斯(51)

这表示父页面“Products”有49个孩子。 “投资组合”有14个等。向这些父页面添加新的子页面会自动更新该数字。

我正在使用wordpress创建的页面的默认菜单,而不是在外观下找到的菜单系统。使用TwentyThirteen主题。

任何?

的Anders

1 个答案:

答案 0 :(得分:2)

在这种情况下,您可以使用walker。将以下类放在functions.php文件

class themeslug_walker_nav_menu extends Walker_Nav_Menu {

    // add main/sub classes to li's and links
    function start_el( &$output, $item, $depth, $args ) {
        global $wp_query;
        $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent

        // depth dependent classes
        $depth_classes = array(
            ( $depth == 0 ? 'main-menu-item' : 'sub-menu-item' ),
            ( $depth >=2 ? 'sub-sub-menu-item' : '' ),
            ( $depth % 2 ? 'menu-item-odd' : 'menu-item-even' ),
            'menu-item-depth-' . $depth
        );
        $depth_class_names = esc_attr( implode( ' ', $depth_classes ) );

        // passed classes
        $classes = empty( $item->classes ) ? array() : (array) $item->classes;
        $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );

        // build html
        $output .= $indent . '<li id="nav-menu-item-'. $item->ID . '" class="' . $depth_class_names . ' ' . $class_names . '">';

        // link attributes
        $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        ) .'"' : '';
        $attributes .= ' class="menu-link ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"';
        $childs = count(get_pages('child_of='.$item->object_id.'&parent='.$item->object_id));
        $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s (%5$s) %6$s</a>%7$s',
            $args->before,
            $attributes,
            $args->link_before,
            apply_filters( 'the_title', $item->title, $item->ID ),
            $childs,
            $args->link_after,
            $args->after
        );

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

并在wp_nav_menu函数

中添加此walker

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

就是这样。

相关问题