我怎样才能做到这一点?我发现count_user_posts 和get_users, 但我如何将它们合并到期望的结果中呢?我真的必须使用WP DB查询吗?
获取至少有一篇帖子为“自定义帖子类型”的所有作者
2 个回复
最合适的回答,由SO网友:Maruti Mohanty 整理而成
目前为止post_type
当前不支持count_user_posts()
,
因此,请将下面的代码放入主题函数中。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 apply_filters( \'get_usernumposts\', $count, $userid );
}
现在这个函数需要user id
和post_type
as参数post_type=\'post\'
作为默认值,并获取相关post\\u类型的该用户的post计数您可以通过回显下面需要用户检查post计数的位置来进行验证。
$user_posts = count_user_posts_by_type( 1, \'page\' );
echo $user_posts; // This would return the post count for user id 1 and post_type page.
您可以对自定义帖子类型执行相同的操作。现在,您需要获取用户ID并通过此函数,并显示具有1个或多个postsor的作者的名称您可以在要显示包含一篇或多篇帖子的用户列表的位置添加以下代码
$blogusers = get_users();
foreach ( $blogusers as $user ) {
if ( count_user_posts_by_type( $user->ID, \'post\') ) {
echo $user->user_nicename . \'</br>\';
}
}
以上代码列出了发布了一篇或多篇帖子的所有用户post_type
post
.SO网友:CoderSantosh
非常旧的查询,但仍然没有直接的方法来获取至少有一篇“自定义帖子类型”帖子的所有作者。WP_User_Query 也不支持post类型。使用$wpdb将解决此问题。
代码:
$post_type = \'gutentor\';/*Your Post type*/
global $wpdb;
$all_authors = $wpdb->get_results(
"
select
A.*, COUNT(*) as post_count
from
$wpdb->users A
inner join $wpdb->posts B
on A.ID = B.post_author
WHERE ( ( B.post_type = \'$post_type\' AND ( B.post_status = \'publish\' OR B.post_status = \'private\' ) ) )
GROUP BY A.ID
ORDER BY post_count DESC"
);
if ( $all_authors ) {
foreach ( $all_authors as $author) {
echo $author->display_name;
}
}
您只需分配$post_type
使用您的帖子类型。结束