I’m looking to count how many post live within the custom post type called “videos”, but only the ones from the category called “work”.
<?php $count_posts = wp_count_posts('videos'); echo $count_posts->publish; // ?>
How can I adjust the above code to accomplish this?
Thanks!
An alternative solution using WP_Query would be:
For a specific custom taxonomy try:
Documentation at https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters
Found a solution.
This also should work:
I know that this is an old thread, but it shows up first in Google, so here is the REAL solution on how to do this.
So you need to pass the ID of the term and the taxonomy. This is the lightest weight solution as well as having the benefit of working with custom taxonomies.
Found this while looking into a similar thing myself so here’s my solution in case it’s useful for anyone else…
Note: Harmonic’s answer works, depending on scenario though it may be easier to do this instead:
$count = get_category($category->term_id)->category_count;
Where
$category
is your taxonomy object.Important note here being that this assumes no other post_type uses the same taxonomy.
Details:
get_category()
is actually a wrapper function ofget_term()
.In this case, get_term() has a name__like parameter that get_category() doesn’t. There are probably other little differences too.
See:
get_term()
get_category
Basically if you do it with your found solution, you will waste quite much DB resources when you have lots of posts to fetch.
However WP_Query->found_posts just fetch ‘posts_per_page’ and do COUNT(*) mysql job for you.
So I recommend you to use the latter one.