0

I have googled this a few different ways, but cannot find the answer I'm looking for. I want to be able to count the number of posts each author has within a custom post type. Any suggestions would be really appreciated

0

i found this code wordpress.org . This code would work in author template.

<?php
global $wp_query;
$curauth = $wp_query->get_queried_object();
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '" . $curauth->ID . "' AND post_type = 'post' AND post_status = 'publish'");
?>
<h2>Post Count: <?php echo $post_count; ?></h2>

But if you wish to use it somewhere else then replace $curauth->ID with author id and post with the post type you want

it should work . All the best

  • I will give this a try. I have seen the $curauth variable used before, but not with the query. Surprised I didn't find this if it was on Wordpress. Thanks! – sgspragg Aug 3 '15 at 20:04
  • :) glad was able to help you – terminator Aug 3 '15 at 20:20
0
 if you're on a single post, it will return the post object
    if you're on a page, it will return the page object
    if you're on an archive page, it will return the post type object
    if you're on a category archive, it will return the category object
    if you're on an author archive, it will return the author object
etc.

Use query-object as suggested by @terminator

In place of using sql query use count_user_posts

  $queried_object = get_queried_object();
    count_user_posts($queried_object->ID, 'custom_post_type_here');
0

Create a function in functions.php

 function count_posts_by_author($post_type){
   global $wp_query;
   $curauth = $wp_query->get_queried_object();
   $args = array(
     'post_type' => $post_type,
     'author'        =>  $curauth->ID,
     'posts_per_page' => -1 // no limit
   );
   echo count(get_posts($args));
 }

and just call the function in your template file

<?php count_posts_by_author('Your post type or custom post type');?>

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.