wp_nav_menu统计自定义后期类型的帖子

时间:2016-10-05 11:25:38

标签: php wordpress custom-post-type

我正在制作一个wordpress投资组合网站。

我想在菜单中自定义帖子类型来统计我的帖子。

这就是我想要实现的目标:

Designs  Films 
 15        20

这是我的菜单代码:

<?php
            if (get_sub_option(GN_SLUG, 'use_bootstrap', false)) {
                wp_nav_menu(array(
                    'menu' => 'top',
                    'theme_location' => 'top',
                    'depth' => 2,
                    'container' => 'div',
                    'container_class' => 'collapse navbar-collapse',
                    'container_id' => 'navbar',
                    'menu_class' => 'nav navbar-nav navbarTop',
                    'fallback_cb' => 'wp_bootstrap_navwalker::fallback',
                    'walker' => new wp_bootstrap_navwalker())


                );
            }
            else {
                wp_nav_menu(array('theme_location' => 'top'));
            }
        ?>

我知道如何计算我的自定义后期类型

$posts = get_posts('post_type= work_content');
$count = count($posts);
echo $count;

但我不知道如何将计数器与菜单结合起来......这可能吗?我怎么处理这个?

谢谢!

2 个答案:

答案 0 :(得分:0)

为了让您了解如何看待这样的沃克,这是一个例子:

class My_Walker_Nav_Menu extends Walker_Nav_Menu {


    /**
     * Ends the element output, if needed.
     *
     * @since 3.0.0
     *
     * @see Walker::end_el()
     *
     * @param string $output Passed by reference. Used to append additional content.
     * @param object $item   Page data object. Not used.
     * @param int    $depth  Depth of page. Not Used.
     * @param array  $args   An array of wp_nav_menu() arguments.
     */
    public function end_el( &$output, $item, $depth = 0, $args = array() ) {

        // var_dump( $item );

        $my_count_slugs = array('films', 'designs');

        if ( in_array( $item->post_name, $my_count_slugs ) ) {
            $count = get_count_from_your_counter_function( $item->post_name );
            $output .= '<div class="count">'. $count .'</div>';
        }

        $output .= "</li>\n";
    }

}

wp_nav_menu()中,您必须立即使用'walker' => new My_Walker_Nav_Menu

get_count_from_your_counter_function()应该返回计数器值(你必须创建这个函数)。

答案 1 :(得分:0)

1)首先,您应该在wordpress.stackexchange.com

询问WP问题

2)关于解决方案:你可以这样做:

add_filter( 'wp_nav_menu_items', function($menu) { 
    $GLOBALS['my_counter_fro_design']= substr_count($menu, 'menu-item-object-Designs');
    $GLOBALS['my_counter_fro_film']= substr_count($menu, 'menu-item-object-Films');
});

然后,在执行wp_nav_menu函数后,您可以:。

var_dump($GLOBALS['my_counter_fro_design']); exit;
相关问题