Show posts count for Categories and Tags in wp_nav_menu

Question

I’m trying to show WooCommerce Product Categories, Post Categories, Product Tags, Post Tags and Custom Taxonomy posts count in main navigation using wp_nav_menu.

My WP_NAV_MENU code

                <?php if( has_nav_menu( 'primary_menu' ) ) : ?>
                    <?php
                        $primary_args = array(
                            'theme_location'    => 'primary_menu',
                            'echo' => false,
                            'depth'             => 3,
                            'container'         => false,
                            'menu_class'        => 'header-menu',
                            'menu_id'           => 'header-menu'
                        );
                        wp_nav_menu( $primary_args );
                    ?>
                <?php endif; ?>

I added the following code into my child-theme functions.php

apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
add_action( 'walker_nav_menu_start_el', 'menu_post_count', 10, 4 );
function menu_post_count( $output, $item, $depth, $args )
{
    // Check $item and get the data you need
    printf( '<pre>%s</pre>', var_export( $item, true ) );
    // Then append whatever you need to the $output
    $output .= '';

    return $output;
}

This caused error on site showing the data of the category as following.

WP_Post::__set_state(array(
   'ID' => 153,
   'post_author' => '1',
   'post_date' => '2015-12-22 21:52:07',
   'post_date_gmt' => '2015-12-22 19:52:07',
   'post_content' => ' ',
   'post_title' => '',
   'post_excerpt' => '',
   'post_status' => 'publish',
   'comment_status' => 'closed',
   'ping_status' => 'closed',
   'post_password' => '',
   'post_name' => '153',
   'to_ping' => '',
   'pinged' => '',
   'post_modified' => '2015-12-29 08:47:30',
   'post_modified_gmt' => '2015-12-29 06:47:30',
   'post_content_filtered' => '',
   'post_parent' => 0,
   'guid' => 'http://domain.com/?p=153',
   'menu_order' => 1,
   'post_type' => 'nav_menu_item',
   'post_mime_type' => '',
   'comment_count' => '0',
   'filter' => 'raw',
   'db_id' => 153,
   'menu_item_parent' => '0',
   'object_id' => '39',
   'object' => 'page',
   'type' => 'post_type',
   'type_label' => 'page',
   'url' => 'http://domain.com/',
   'title' => 'homepage',
   'target' => '',
   'attr_title' => '',
   'description' => '',
   'classes' => 
0
, , , , WiTon Nope 3 years 2020-05-29T04:10:34-05:00 0 Answers 108 views 0

Leave an answer

Browse
Browse