I have this shortcode which displays total number of posts from a custom taxonomy, but I need it to work on Archive pages, so if I don't put an ID to the shortcode, it doesn't display.
function category_product_count_shortcode( $atts ) {
$atts = shortcode_atts( array(
'id' => '',
), $atts );
$category = get_term( $atts['id'], 'product_cat' );
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $category->term_id,
),
),
);
$query = new WP_Query( $args );
$count = $query->post_count;
return $count;
}
add_shortcode( 'category_product_count', 'category_product_count_shortcode' );
Shortcode would be [category_product_count id="12"]
Here is the modified of your code. You have to get category from the archive page.
function category_product_count_shortcode( $atts ) {
$atts = shortcode_atts( array(
'id' => '',
), $atts );
// Check if ID parameter is provided, if not, get the category from the current Archive page
if ( empty( $atts['id'] ) && is_tax( 'product_cat' ) ) {
$category = get_queried_object();
} else {
$category = get_term( $atts['id'], 'product_cat' );
}
if ( ! $category ) {
return ''; // Return an empty string if the category is not found
}
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $category->term_id,
),
),
);
$query = new WP_Query( $args );
$count = $query->post_count;
return $count;
}
add_shortcode( 'category_product_count', 'category_product_count_shortcode' );