Ask your WordPress questions! Pay money and get answers fast! (more info)

Display post count next to category in custom menu WordPress

  • SOLVED

I have created a menu in admin that I want to use to show a list of certain categories in my own order.

Using a custom menu widget I can display this list.

How do I display the post count next to each category and also have the category name display as the link title when you hover on the link?

Answers (2)

2015-11-25

Hai Bui answers:

Insert the below code to your theme's functions.php, it will add a custom Walker to the menu to add the post count and link title attribute. Please replace 'Category Nav' with your menu name


function custom_nav_args($args){
if($args['menu'] && $args['menu']->name == 'Category Nav') { // replace 'Category Nav' with your menu name
$args['walker'] = new Custom_Category_Menu_Walker();
}
return $args;
}
add_filter('wp_nav_menu_args', 'custom_nav_args');


class Custom_Category_Menu_Walker extends Walker_Nav_Menu {
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;

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

$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

$output .= $indent . '<li' . $id . $class_names .'>';


$atts = array();
$atts['title'] = ! empty( $item->title ) ? $item->title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
$atts['href'] = ! empty( $item->url ) ? $item->url : '';

$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );

$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( ! empty( $value ) ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}

if ($item->object == 'category') {
$category = get_category($item->object_id);
}
$item_output = '<a'. $attributes .'>';
$item_output .= apply_filters( 'the_title', $item->title, $item->ID ) . (!empty($category)?" ({$category->count})":"");
$item_output .= '</a>';

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


}


julesphoto comments:

Thank you Hai Bui. That has answered my question perfectly.

2015-11-25

Reigel Gallarde answers:

is custom menu widget a plugin? do you have a link to this plugin?
we need to know how the plugin was implemented..


julesphoto comments:

The custom menu widget comes packaged with the standard installation of wordpress.