Skip to content

Instantly share code, notes, and snippets.

@kloon
Created December 5, 2012 19:13
Show Gist options
  • Save kloon/4218605 to your computer and use it in GitHub Desktop.
Save kloon/4218605 to your computer and use it in GitHub Desktop.
WooCommerce Product Count Shortcode
// [product_count] shortcode
function product_count_shortcode( ) {
$count_posts = wp_count_posts( 'product' );
return $count_posts->publish;
}
add_shortcode( 'product_count', 'product_count_shortcode' );
@pipolocosisi
Copy link

Ditto the request for a shortcode to provide a count of products in a designated category. For example, the shortcode call could look like this:
[woocommerce_product_category_count category="christmas"]
Many thanks to whoever can help with this.

You can use:
// [products-counter category="28"]
add_shortcode( 'products-counter', 'products_counter' );
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 '';
}

I'd like to use this to bypass the woocommerce product counter (which is not displayed for obscure reasons)

How can I add static text in the result to be displayed like "There are X product(s)"?

@vkartk
Copy link

vkartk commented Jan 17, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment