Site logo

Archived topic

Easy way to exclude a category from post count?

3 replies · Started by Igor on December 10, 2021

Viewing posts 1–4 of 4

Hello dear support team,

I have been using this:

add_shortcode( 'total_posts', function() {
    ob_start();
    // Start your PHP below
	
	$post_count_published = wp_count_posts()->publish;
echo "<b>$post_count_published</b>";
	
    // End your PHP above
    return ob_get_clean();
} );

to display total count of recipes on my page. But now I plan to include a special category "blog" that I want to exclude from this count.

Is it possible to amend the code above in an easy way or would this require more complex solution?

Thanks!

Hi Igor,

Give this snippet a try:

add_shortcode( 'total_posts', function() {
ob_start();
// Start your PHP below

$post_count_published = wp_count_posts()->publish;
$cat_count = get_category(get_cat_ID('blog'))->count;

$post_count_exlude_cat = $post_count_published - $cat_count;
echo "<b>$post_count_exlude_cat</b>";

// End your PHP above
return ob_get_clean();
} );

Thank you Ying, works like a charm!

You are welcome :)

This archived topic is closed to new replies.