最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

count - Counting posts in custom post type by author

programmeradmin3浏览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

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

Share Improve this question asked Aug 3, 2015 at 19:53 sgspraggsgspragg 1572 silver badges11 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 0

i found this code wordpress . 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

<?php
// get author ID
$author_id = get_the_author_meta( 'ID' ); 

// echo count for post type (post and book)
echo  count_user_posts( $author_id , ['post','book']  ); 

?>
 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');

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');?>
发布评论

评论列表(0)

  1. 暂无评论