WordPress函数的默认版本提供默认帖子类型“post”的计数,如下所述:
<?php
$post_count = count_user_posts($userid);
?>
要根据帖子类型检索帖子计数,需要一个自定义函数,如下所示:
<?php
function count_user_posts_by_type( $userid, $post_type = \'post\' ) {
global $wpdb;
$where = get_posts_by_author_sql( $post_type, true, $userid );
$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
return $count;
}
?>
上述功能的使用:
<?php
$post_count = count_user_posts_by_type($userid, $post_type);
?>
现在,当您获得post计数时,请将代码包装在条件循环中。
如何在功能中使用:
<?php
// count number of Articles (CPT) written by a user
function count_user_posts_by_type( $userid, $post_type = \'publication\' ) {
global $wpdb;
$where = get_posts_by_author_sql( $post_type, true, $userid );
$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
return $count;
}
$allUsers = get_users(\'orderby=title&order=ASC&post_type=publication\');
$users = array();
// Remove subscribers from the list as they won\'t write any articles
foreach($allUsers as $currentUser)
{
if(!in_array( \'subscriber\', $currentUser->roles ))
{
$users[] = $currentUser;
}
}
foreach($users as $user) {
$post_count = count_user_posts_by_type($user->id);
if ($post_count > 0 { ?>
<div class="authorInfo">
<h2 class="authorName"><?php echo $user->display_name; ?></h2>
<?php query_posts( array( \'post_type\' => \'publication\', \'showposts\' => -1, \'author\'=>$user->ID ) );
while (have_posts()) : the_post();
the_content();
endwhile; ?>
</div>
<?php }
}
?>