Ограничить количество пользователей, возвращенных функцией сортировки пользователей по последним публикациям


Я использую этот фрагмент кода здесь из этой темы: Упорядочивайте пользователей по дате их последнего сообщения. Но мне нужно передать "число" и "смещение" в $args, чтобы разбить на страницы и ограничить количество возвращаемых пользователей. Когда я передаю эти аргументы в get_users_ordered_by_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;
    }

***** ОБНОВЛЕНИЕ: Я только что понял что описанная выше функция не будет работать в моем случае, я не хочу, чтобы она ограничивала количество пользователей, а затем сортировала только их. Так что функция, вероятно, не то решение, которое я ищу. Что я ищу, так это отобразить 6 пользователей на главной странице (отсортированных по их последним публикациям) и на странице, где отображаются все пользователи, разбить эту страницу на страницы. Я не уверен, как это сделать, поэтому я обновлю вопрос своим текущим кодом:

//display each author's name, avatar and their one latest post
add_action ('genesis_before_content_sidebar_wrap', 'pc_author_posts', 15);
//NEED A FUNCTION THAT SORT USERS BY THEIR LATEST POSTS' DATES HERE


function pc_author_posts() {
if( (is_front_page()) | (is_page('latest-posts-from-our-readers')) ) {
?>
<div class="pc-author-outer">
<?php
if(is_front_page()) {
echo '<div class="pc-author-heading-line">';
echo '<h4 class="pc-author-heading">Latest Posts From Our Readers</h4>';
echo '
<h6 class="pc-author-more"><a href="http://localhost/.../latest-posts-from-our-readers/" alt="See all latest posts from all of our readers">
More >></a></h6>';
echo '</div>';
$authors=get_users('number=6');
}
elseif(is_page('all-latest-posts')) {
$number = 9;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$offset = ($paged - 1) * $number;
$usersnumber=get_users();
$authors= get_users('offset='.$offset.'&number='.$number.'&order=DESC');
$total_users = count($usersnumber);
$total_query = count($query);
$total_pages = intval($total_users / $number) + 1;
}
$i=0;
//get all users list
foreach($authors as $author){
$authorList[$i]['id']=$author->data->ID;
$authorList[$i]['name']=$author->data->display_name;
$authorList[$i]['url']=get_author_posts_url($author->ID);
$authorList[$i]['avatar'] = get_avatar($author->ID, 70);
$i++;
}
?>
<ul class="pc-authors-wrap" id="pc-authors-wrap">
<?php
foreach($authorList as $author){
$args=array(
'showposts'=>1,
'author'=>$author['id'],
);
$query = new WP_Query($args);
if($query->have_posts() ) {
while ($query->have_posts()){
$query->the_post();
?>

<li class="pc-authors one-third">
<!--<div class="pc-post-line"> -->

<div class="pc-author-line">
<h2 class="pc-author-title"><a href="<?php echo get_permalink(); ?>"> <?php echo get_the_title(); ?></a></h2>
<div class="pc-rating">
<?php
$pid = $post->ID;
if(function_exists("kk_star_ratings")) : echo kk_star_ratings($pid);
endif; 
?>
</div>

<div class="pc-author-avatar"><a href="<?php echo $author['url']; ?>"><?php echo $author['avatar']; ?></a></div>

<small><a href="<?php echo $author['url']; ?>"><?php echo $author['name']; ?></a></small>
<p><a href="<?php echo get_permalink(); ?>"> <?php echo excerpt(40); ?> ... [read more]</a></p>
</div>
<a class="pc-author-img" href="<?php echo get_permalink(); ?>"><?php echo the_post_thumbnail('post-small'); ?></a>

</li>
<?php
}
}
wp_reset_postdata();
}
?>
<li class="pc-authors clearfix"></li>
</ul>
<?php
if ($total_users > $total_query) {
echo '<div id="pagination" class="author-pagination">';
$current_page = max(1, get_query_var('paged'));
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => 'page/%#%/',
'current' => $current_page,
'total' => $total_pages,
'prev_next'    => true,
'prev_text'          => __('« Previous Page'),
'next_text'          => __('Next Page »'),
'type'         => 'plain',
));
echo '</div>';
?>
</div>
<?php
}
?>
<?php
}
}

****ОБНОВЛЕНИЕ 2-Й РАЗ: Получилось! Я использую код от @inarilo и изменил мой код, как показано ниже:

//display each author's name, avatar and their one latest post
add_action ('genesis_before_content_sidebar_wrap', 'pc_author_posts', 15);
//SORTING FUNCTION
function get_users_ordered_by_post_date($offs=0, $lim=10, $ord='DESC') {
  global $wpdb;
  if(!is_numeric($offs) || !is_numeric($lim) || !in_array(strtoupper($ord), array('ASC','DESC'))) return array();
  $q = "SELECT DISTINCT post_author FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date {$ord} LIMIT {$offs}, {$lim}";
  $users = $wpdb->get_results($q, ARRAY_N);
  foreach($users as $i => $u) $users[$i] = get_userdata($users[$i][0]);
  return $users;
}

function pc_author_posts() {
if( (is_front_page()) | (is_page('all-latest-posts')) ) {
?>
<div class="pc-author-outer">
<?php
if(is_front_page()) {
echo '<div class="pc-author-heading-line">';
echo '<h4 class="pc-author-heading">All Latest Posts</h4>';
echo '
<h6 class="pc-author-more"><a href="http://localhost/.../latest-posts-from-our-readers/" alt="See all latest posts">
More >></a></h6>';
echo '</div>';

$authors = get_users_ordered_by_post_date(0,6);

}
elseif(is_page('latest-posts-from-our-readers')) {
$lim = 9;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$offs = ($paged - 1) * $lim;
$users= get_users_ordered_by_post_date(0,9999);
$authors= get_users_ordered_by_post_date($offs,$lim);
$total_users = count($users);
$total_query = count($query);
$total_pages = intval($total_users / $lim) + 1;
}
$i=0;
//get all users list
foreach($authors as $author){
$authorList[$i]['id']=$author->data->ID;
$authorList[$i]['name']=$author->data->display_name;
$authorList[$i]['url']=get_author_posts_url($author->ID);
$authorList[$i]['avatar'] = get_avatar($author->ID, 70);
$i++;
}
?>
<ul class="pc-authors-wrap" id="pc-authors-wrap">
<?php
foreach($authorList as $author){
$args=array(
'showposts'=>1,
'author'=>$author['id'],
);
$query = new WP_Query($args);
if($query->have_posts() ) {
while ($query->have_posts()){
$query->the_post();
?>

<li class="pc-authors one-third">
<!--<div class="pc-post-line"> -->

<div class="pc-author-line">
<h2 class="pc-author-title"><a href="<?php echo get_permalink(); ?>"> <?php echo get_the_title(); ?></a></h2>
<div class="pc-rating">
<?php
$pid = $post->ID;
if(function_exists("kk_star_ratings")) : echo kk_star_ratings($pid);
endif; 
?>
</div>

<div class="pc-author-avatar"><a href="<?php echo $author['url']; ?>"><?php echo $author['avatar']; ?></a></div>

<small><a href="<?php echo $author['url']; ?>"><?php echo $author['name']; ?></a></small>
<p><a href="<?php echo get_permalink(); ?>"> <?php echo excerpt(40); ?> ... [read more]</a></p>
</div>
<a class="pc-author-img" href="<?php echo get_permalink(); ?>"><?php echo the_post_thumbnail('post-small'); ?></a>

</li>
<?php
}
}
wp_reset_postdata();
}
?>
<li class="pc-authors clearfix"></li>
</ul>
<?php
if ($total_users > $total_query) {
echo '<div id="pagination" class="author-pagination">';
$current_page = max(1, get_query_var('paged'));
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => 'page/%#%/',
'current' => $current_page,
'total' => $total_pages,
'prev_next'    => true,
'prev_text'          => __('« Previous Page'),
'next_text'          => __('Next Page »'),
'type'         => 'plain',
));
echo '</div>';
?>
</div>
<?php
}
?>
<?php
}
}
 1
Author: fuxia, 2017-05-31

1 answers

function get_users_ordered_by_post_date($offs=0, $lim=10, $ord='DESC') {
  global $wpdb;
  if(!is_numeric($offs) || !is_numeric($lim) || !in_array(strtoupper($ord), array('ASC','DESC'))) return array();
  $q = "SELECT DISTINCT post_author FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date {$ord} LIMIT {$offs}, {$lim}";
  $users = $wpdb->get_results($q, ARRAY_N);
  foreach($users as $i => $u) $users[$i] = get_userdata($users[$i][0]);
  return $users;
}

ARRAY_N задает возвращаемые типы в виде массива неассоциативных массивов.

 0
Author: inarilo, 2017-06-01 05:05:22