WooCommerce Get Item count on a category page

Question

I want to display a count of items in my header, a count of how many items are in the current category…

Example:
User goes to "T Shirts" > in the header it says "20 Items" — They go to "Hoodies" > Header says "10 Items"

I’m currently using a shortcode and code in functions.php:

function products_counter( $atts ) {
    $atts = shortcode_atts( [
        'category' => '',
    ], $atts );

    $taxonomy = 'product_cat';
    if ( is_numeric( $atts['category'] ) ) {
        $cat = get_term( $atts['category'], $taxonomy );
    } else {
        $cat = get_term_by( 'slug', $atts['category'], $taxonomy );
    }

    if ( $cat && ! is_wp_error( $cat ) ) {
        return $cat->count;
    }
    return '';
}

Which works great if I define the product category in the shortcode… My issue is it’s in the header, so all category pages say the same item count… Is there a way to get it to display based on url?

0
Aaron Bradford 2 years 2020-12-31T00:11:04-05:00 0 Answers 2 views 0

Leave an answer

Browse
Browse