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"]
2
Answers
You can test if
$atts['id']
exists and if so construct thetax_query
array.Here is the modified of your code. You have to get category from the archive page.