0

I want to count authors post count in a specific category. How do i do that? I have red this thread here but still can't fiure it out.

Count number of posts by author in a category

Edit: This is what i got and tried but doesnt work at all.

$user_id = get_the_author_meta('ID')

$args = array(
   'author_name'   => $user_id,
   'category_name' => 'categoryname',
};               
        $wp_query = new WP_Query($args);
while ( $wp_query->have_posts() ) : $wp_query->the_post();
        
            echo $my_count = $wp_query->post_count;
            
wp_reset_postdata();    
endwhile;
0
0

You don't need to loop through the posts for this.

Instead, just call the method get_posts() which will return an array of posts and then just count the number of posts in that array.

$user_id = get_the_author_meta('ID');

$args = array(
   'author_name'   => $user_id,
   'category_name' => 'categoryname',
);               
$wp_query = new WP_Query($args);

$posts = $wp_query->get_posts();
$my_count = count( $posts );
echo $my_count;

Reference

https://developer.wordpress.org/reference/classes/wp_query/get_posts/

4
  • I get result 0. Category name is correct. – ANdy Feb 27 at 16:54
  • Maybe you need a few more parameters to find the correct posts. Have a look through developer.wordpress.org/reference/classes/wp_query/#parameters and see if there's anything in your posts that won't be found by the defaults. In particular consider post_status and post_type. – Andrew Real Feb 28 at 11:58
  • What i can be missing? Im tryin to find out but can't understand what im missing. – ANdy Feb 28 at 12:20
  • Problem was 'author_name' should be 'author' but wierd thing is taht your code prints all posts also which i don't want and also never ends printing them. How to fix these issues? – ANdy Mar 4 at 11:10
0

Here is the correct code. It shows authors post count from a specific category by category slug name.

$user_id = get_the_author_meta('ID');

$args = array(
   'author'   => $user_id,
   'category_name' => 'category_slug_name',
);    
 
$my_query = new WP_Query( $args );
$my_count = $my_query->post_count;

echo $my_count; 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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