wordpress tips

How to display count products in each categories ( menu )

Add this code to your functions.php file on theme folder :

 

add_shortcode( ‘cat-counter’, ‘libar_return_current_category_counter’ );
function libar_return_current_category_counter() {
   $category = is_product_category() ? get_queried_object() : false;
   return $category ? $category->count : false;
}
function libar_menu_item_count( $output, $item, $depth, $args ) {
    // Check if the item is a Product Category or Custom Taxonomy
    if( $item->type == ‘taxonomy’ ) {
        $object = get_term($item->object_id, $item->object);
        // Check count, if more than 0 display count
        if($object->count > 0) {
            $output_new = ”;
            $output_split = str_split($output, strpos($output, ‘</a>’) );
            $output_new .= $output_split[0] . “<span class=’menu-item-count’> (“.$object->count.”)</span>” . $output_split[1];
            $output = $output_new;
        }
    }
    return $output;
}
add_action( ‘walker_nav_menu_start_el’, ‘libar_menu_item_count’, 10, 4 );

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Share with your friends