wordpress收费下载资源主题
wordpress付费下载资源插件

wordpress基于发布的文章数倒序输出作者orderby=post_count不生效的解决办法

最近发现wordpress官方的wp_user_query里所给出的'orderby' => 'post_count'这个排序根本不生效。

使用下面代码始终没法基于文章数量排序:

$authors = get_users( 
array( 
'role' => 'author' ,
'number' => $perpage,
'offset' => $offset,
'paged' => $paged,
'orderby' => 'post_count', 
'order' => 'DESC'
) 
);

基于模板兔一翻搜索,终于找到了解决方案,不要一直纠结官方的orderby=post_count了,这根本就是个大bug,只能自己另写代码实现。

代码如下供大伙参考:

$authors = get_users(array(
    'role' => 'author',
    'orderby' => 'post_count',
    'order' => 'DESC',
));

$sorted_authors = [];

foreach ($authors as $author) {
    $author->post_count = count_user_posts($author->ID);
    $sorted_authors[$author->ID] = $author;
}

usort($sorted_authors, function($a, $b) {
    return $b->post_count - $a->post_count;
});

foreach ($sorted_authors as $author) {
    echo $author->display_name . ' - ' . $author->post_count . ' posts<br>';
}

先使用get_users()函数获取作者用户列表,然后遍历每个作者并为每个作者创建了一个新的属性post_count,并将其设置为对应的文章数量。然后,我使用usort()函数根据post_count属性对作者进行自定义排序。

最后,我按照排序后的结果输出作者列表就是基于文章数排序了。

0 个评论

定制开发
本站承接WordPress等系统建站仿站、二次开发、主题插件定制等开发服务
在线咨询
  • 请直接说明需求,勿问在否
    QQ:1-247-246-247

  • QQ一群:104228692(满)
  • QQ二群:64786792
在线咨询
本站承接WordPress建站仿站、二次开发、主题插件定制等PHP开发服务!

了解详情