Skip to content

Instantly share code, notes, and snippets.

@vkartk
Created January 17, 2022 07:18
Show Gist options
  • Save vkartk/c821b96845998375769dcabfcc9c8ff5 to your computer and use it in GitHub Desktop.
Save vkartk/c821b96845998375769dcabfcc9c8ff5 to your computer and use it in GitHub Desktop.
WooCommerce Product Count By Category || Shortcode
// To Only Retrun the Product Count By Category
//[woocommerce_product_category_count category="rings"]
// Special thanks to CHADREX
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 '';
}
// To Only Retrun the Product Count By Category for only IN STOCK products
//[woocommerce_product_category_count category="rings"]
// Special thanks to SevenAxis
add_shortcode( 'products-counter', 'products_counter' );
function products_counter( $atts ) {
$atts = shortcode_atts( [
'category' => '',
], $atts );
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $atts['category']
)
),
'meta_query' => array(
array(
'key' => '_stock_status',
'value' => 'instock'
),
)
);
$query = new WP_Query($args);
$inStockCount = $query->found_posts;
if ( $query && ! is_wp_error( $query ) ) {
return $inStockCount;
}
return '';
}
// Retrun the Product Count By Category as There are X product(s)"
//[woocommerce_product_category_count category="rings"]
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 ) ) {
$catstring = "There are ".$cat->count." product(s)";
return $catstring;
}
return '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment