1

I use this code snippet here from this thread: Order the users by the date of their latest post . But I need to pass in the "number" and "offset" into $args to paginate and limit the number of users returned. When I pass these arguments into get_users_ordered_by_post_date(), the function doesn't sort users by the date of their latest posts anymore. Any solutions to make this work would be appreciated!

    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;
    }

***** UPDATE:I've just realized that the function above won't work for my case , I don't want it to limit the number of users then sort only them. So the function is probably not the solution I'm looking for. What I'm looking for is to display 6 users on the front page (sorted by their latest posts) and on the page where all users are displayed, paginate that page. I'm not sure how to do that though, so I will update the question with my current code:

//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
}
}

****UPDATE 2ND TIME: Got it working! I'm using the code from @inarilo and have modified my code as below:

//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
}
}
7
  • So you're asking how to paginate/slice a possible very large PHP array?
    – birgire
    May 31 '17 at 9:46
  • passing those values limits the users returned by get_users, and then only those users are sorted by their latest posts.
    – inarilo
    May 31 '17 at 15:59
  • I've just realized that @inarilo , I don't want it to limit the number of users then sort only them. So the function is probably not the solution I'm looking for. What I'm looking for is to display 6 users on the front page (sorted by their latest posts) and on the page where all users are displayed, paginate that page. I'm not sure how to do that though, so I will update the question with my current code. May 31 '17 at 16:08
  • And it's not a very large array now (about 40 users) @birgire but of course I'd like to find the best solution in terms of performance. May 31 '17 at 16:08
  • you can just modify the function but best might be using your own sql codex.wordpress.org/Class_Reference/wpdb
    – inarilo
    May 31 '17 at 16:35
0
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 sets the return typs as an array of non-associative arrays.

12
  • 1
    We should watch out for possible SQL injections
    – birgire
    May 31 '17 at 20:43
  • added parameter checks
    – inarilo
    May 31 '17 at 21:44
  • Hi @inarilo , thanks so much for your quick answer, the code looks so neat and I hope we can make it work! I have placed your code in and call the function as below, it works like a charm on the front page (where I only need 6 posts), but it throws an "Invalid argument supplied for foreach()" error on my foreach($authors as $author) loop on the other page where I need the pagination, my modified code looks like below: $authors= get_users_ordered_by_post_date($offset.','.$number); Did I miss something? Jun 1 '17 at 3:02
  • it appears you are passing a string with two numbers, the function takes separate arguments for offset, limit (i.e. how many records to return) and the order (all optional, though it just now occurred to me the default limit should be 10 instead of 0 :)
    – inarilo
    Jun 1 '17 at 3:11
  • 1
    I just realized that the sorting didn't sort correctly ( it seemed like it did by putting the very latest post on top, but the following posts didn't sort correctly, I have added this line to your code: WHERE post_status = 'publish' AND post_type = 'post' and it seems to sort fine now. Check out my updated code. Jun 1 '17 at 4:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.