wordpress的get_users是获取用户列表的,我们可以获取所有角色是author的用户,但是这个排序却没有基于最新发布文章时间(get_users order by author last post date)来排序用户列表的。
我们可以通过以下函数来实现:
function get_users_ordered_by_post_date($args = '') {
// Prepare arguments
if (is_string($args) && '' !== $args)
parse_str($args, $args);
$asc = (isset($args['order']) && 'ASC' === strtoupper($args['order']));
unset($args['orderby']);
unset($args['order']);
// Get ALL users
$users = get_users($args);
$post_dates = array();
if ($users) {
// For EACH user ...
foreach ($users as $user) {
$ID = $user->ID;
// ... get ALL posts (per default sorted by post_date), ...
$posts = get_posts('author='.$ID);
$post_dates[$ID] = '';
// ... then use only the first (= newest) post
if ($posts) $post_dates[$ID] = $posts[0]->post_date;
}
}
// Sort dates (according to order), ...
if (! $asc)
arsort($post_dates);
// ... then set up user array
$users = array();
foreach ($post_dates as $key => $value) {
// $user = get_userdata($key);
// $users[] = $user->ID;
$users[] = get_userdata($key);
}
return $users;
}
将get_users替换为get_users_ordered_by_post_date即可,参数还是传入一个$args。
有一点需要注意的时,如果要分页获取作者列表,需对数组进行分页。
$authors = get_users_ordered_by_post_date(
array(
'role__in' => array( 'author' )
)
);
if($authors){
$perpage = 16;
$pagess = ceil(count($authors) / $perpage);
if (!get_query_var('paged')) {
$paged = 1;
}else{
$paged = $wpdb->escape(get_query_var('paged'));
}
$offset = $perpage*($paged-1);
$authors2 = array_slice($authors,($paged-1)*$perpage,$perpage);
if($authors2){
foreach($authors2 as $author){
}
}
}
有种排序有个问题就是当用户以及文章越来越多时,数据查询的时间会越来越长,也就是可能会卡。
原文链接:https://www.dqzy.cn/2025/04/16/401.html,转载请注明出处。
1、本站所有源码资源(包括源代码、软件、学习资料等)仅供研究学习以及参考等合法使用,请勿用于商业用途以及违法使用。如本站不慎侵犯您的版权请联系我们,我们将及时处理,并撤下相关内容!
2、访问本站的用户必须明白,本站对所提供下载的软件和程序代码不拥有任何权利,其版权归该软件和程序代码的合法拥有者所有,请用户在下载使用前必须详细阅读并遵守软件作者的“使用许可协议”,本站仅仅是一个学习交流的平台。
3、如下载的压缩包需要解压密码,若无特殊说明,那么文件的解压密码则为:www.dqzy.cn。
4、点启资源网是一个免费且专业分享网站源码、图片素材、特效代码、教程文章、站长工具的平台。我们努力给站长提供好的资源!


评论0