WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!

share|improve this question

An alternative solution using WP_Query would be:

$args = array(
  'cat' => 4,
  'post_type' => 'videos'
);
$the_query = new WP_Query( $args );
echo $the_query->found_posts;
share|improve this answer

Found a solution.

<?php $posts = get_posts('post_type=videos&category=4'); 
$count = count($posts); 
echo $count; 
?>
share|improve this answer
1  
Really bad idea. What if you have 15000 posts? You put them ALL in memory? These are the kind of misconceptions that could wreck a production site. – Cranio Mar 4 at 15:12

For a specific custom taxonomy try:

$the_query = new WP_Query( array(
    'post_type' => 'CUSTOM_POST_TYPE',
    'tax_query' => array(
        array(
            'taxonomy' => 'CUSTOM_TAXONOMY',
            'field' => 'id',
            'terms' => TERM_ID
        )
    )
) );
$count = $the_query->found_posts;

Documentation at https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

share|improve this answer

This also should work:

$category = get_term('work', 'category');
$posts_in_category = $category->count;
share|improve this answer
2  
This will fail if the a taxonomy is assined to more than one post type and you just need the post count of one post type – Pieter Goosen Nov 10 '15 at 9:15

Basically if you do it with your found solution, you will waste quite much DB resources when you have lots of posts to fetch.

$query = new WP_Query();
echo $query->found_posts();

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.