在我的 WordPress v5.8.1 中,我有一个在自定义帖子song和poem. 使用下面的代码,我可以获得在两个或一个自定义帖子中发布的作者列表。
$authors = get_users(array(
'who' => 'authors',
'has_published_posts' => array('song','poem'),
'orderby' => 'post_count',
'order' => 'DESC',
'number' => '15'
));
Run Code Online (Sandbox Code Playgroud)
下面的代码列出了所有作者及其帖子数:
foreach ($authors as $user) {
$name = $user->first_name . ' ' . $user->last_name;
$songs = count_user_posts($user->ID, $post_type = "song");
$poems = count_user_posts($user->ID, $post_type = "poem");
echo $name.' has '. $songs .' songs, and '. $poems .' poems;
}
Run Code Online (Sandbox Code Playgroud)
在参数中'orderby' => 'post_count',我希望首先显示组合自定义帖子数最高的作者列表,但它是随机显示的,没有顺序,既不是 bypost_counts也不是ID。
如何对帖子总数最多的作者进行排序?
尝试下面的代码。
$authors = get_users(array(
'who' => 'authors',
'has_published_posts' => array('song','poem'),
'orderby' => 'post_count',
'order' => 'DESC',
'number' => '15'
));
Run Code Online (Sandbox Code Playgroud)
创建一首array并计算诗歌+歌曲的总数
$author_posts = array();
foreach ($authors as $user) {
$name = $user->first_name . ' ' . $user->last_name;
$songs = count_user_posts($user->ID, $post_type = "song");
$poems = count_user_posts($user->ID, $post_type = "poem");
$author_posts[] = array(
'total' => $songs+$poems,
'label' => $name.' has '. $songs .' songs, and '. $poems .' poems'
);
}
Run Code Online (Sandbox Code Playgroud)
现在使用 `usort 按总计对数组进行排序。
usort($author_posts, function($a, $b) {
if($a['total']==$b['total']) return 0;
return $a['total'] < $b['total']?1:-1;
});
Run Code Online (Sandbox Code Playgroud)
打印输出。
foreach ( $author_posts as $key => $author_post ) {
echo $author_post['label']."</br>";
}
Run Code Online (Sandbox Code Playgroud)
完整代码。
$authors = get_users(array(
'who' => 'authors',
'has_published_posts' => array('song','poem'),
'orderby' => 'post_count',
'order' => 'DESC',
'number' => '15'
));
$author_posts = array();
foreach ($authors as $user) {
$name = $user->first_name . ' ' . $user->last_name;
$songs = count_user_posts($user->ID, $post_type = "song");
$poems = count_user_posts($user->ID, $post_type = "poem");
$author_posts[] = array(
'total' => $songs+$poems,
'label' => $name.' has '. $songs .' songs, and '. $poems .' poems'
);
}
usort($author_posts, function($a, $b) {
if($a['total']==$b['total']) return 0;
return $a['total'] < $b['total']?1:-1;
});
foreach ( $author_posts as $key => $author_post ) {
echo $author_post['label']."</br>";
}
Run Code Online (Sandbox Code Playgroud)
经过测试并有效。
您的块内有错误foreach,这可能是导致问题的原因。使用这个代替:
foreach ($authors as $user) {
$name = $user->first_name . ' ' . $user->last_name;
$songs = count_user_posts($user->ID, "songs");
echo $name.' has '. $songs .' songs ';
}
Run Code Online (Sandbox Code Playgroud)
简而言之,$post_type = "songs"只需将替换为"songs"。有关接受的参数的详细信息,请参阅文档。
编辑:我误解了这个问题。看看你的查询,一切都应该如此,所以我会在其他地方寻找问题的根源。您是否有可能更改查询的插件或过滤器?您可以直接在数据库中重现您的查询吗?它可以在那里工作吗?(以排除表或索引损坏)