admin管理员组

文章数量:1302318

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;

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;
Share Improve this question edited Feb 27, 2021 at 16:53 ANdy asked Feb 27, 2021 at 1:30 ANdyANdy 478 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 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/reference/classes/wp_query/get_posts/

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; 

本文标签: categoriesAuthor post count in category