我发现可以按照每个用户拥有的帖子数量对用户查询进行排序,但是可以从结果中排除没有帖子的用户吗?在Wp\\u User\\u Query类中pre_user_query
操作,但查询字符串是一个巨大的弱点,所以我不确定我想在这里使用哪种类型的过滤操作。
WP_USER_QUERY以排除无帖子的用户
3 个回复
最合适的回答,由SO网友:helgatheviking 整理而成
我想出了两个解决方案。
Solution 1 - foreach loop and verify each user
这个基于@GhostToast的解决方案,但具有更新的WordPress功能//new query with default args
$author_query = new WP_User_Query();
// Get the results
$authors = $author_query->get_results();
if( $authors ) {
foreach( $authors as $author ) {
if ( count_user_posts( $author->id ) >= 1 ) {
echo $author->display_name . \'</br>\';
}
}
} else {
echo "no users found";
}
Solution 2 - fancy pants pre_user_query
action
pre_user_query
中的操作WP_User_Query
班如果你过去post_count
作为您的orderby
参数,然后一些我自己永远不会想到的奇特的SQL查询碰巧将适当的表连接在一起。所以我所做的就是复制join语句并将其添加到我自己的语句中。如果我可以在添加它之前先检查它的存在,这会更好。。。也许我将来会使用字符串匹配。但现在,因为我是设置查询的人,我知道它不在那里,我只是暂时不担心它。所以代码是这样的:function authors_with_posts( $query ) {
if ( isset( $query->query_vars[\'query_id\'] ) && \'authors_with_posts\' == $query->query_vars[\'query_id\'] ) {
$query->query_from = $query->query_from . \' LEFT OUTER JOIN (
SELECT post_author, COUNT(*) as post_count
FROM wp_posts
WHERE post_type = "post" AND (post_status = "publish" OR post_status = "private")
GROUP BY post_author
) p ON (wp_users.ID = p.post_author)\';
$query->query_where = $query->query_where . \' AND post_count > 0 \';
}
}
add_action(\'pre_user_query\',\'authors_with_posts\');
然后使用它$args = ( array( \'query_id\' => \'authors_with_posts\' ) );
$author_query = new WP_User_Query( $args );
关于query_id
参数来自简介WP_User_Class这也是一个很好的参考WP_User_Query
SO网友:pixeline
从4.4开始,只需使用“has\\u published\\u posts”参数即可。
示例:
$authors = get_transient(\'mytheme_all_authors\');
if (empty($authors)){
$user_args = array(
\'role__in\' => array(\'Author\', \'Administrator\', \'Contributor\'),
\'orderby\' => \'post_count\',
\'order\' => \'DESC\',
\'count_total\' => true,
\'has_published_posts\' => array(\'post\'),
);
$authors = new WP_User_Query( $user_args );
set_transient(\'mytheme_all_authors\', $authors, 1 * HOUR_IN_SECONDS );
}
$total= $authors->get_total();
$authors = $authors->results;
foreach ( $authors as $user) {
// loop through your users....
has_published_posts
可以是true/false(或null),也可以是post类型的数组(如本例中所示)。注意:我在这里使用的是瞬态,因为这个特定的查询可能会变得很重,这取决于系统,所以存储它以备将来使用是有意义的。
SO网友:GhostToast
提交作为关闭答案:
$all_members = get_users();
foreach($all_members as $member){
$post_count = count_user_posts($member->ID);
if(empty($post_count)) {
$bad_writers[] = $member->ID;
continue;
} else {
// do something;
}
}
结束