0

I cannot use the 'orderby' => 'post_count' as contributors have multiple posts assigned to them.

Rather, for each user output, I get their $post_count using the count_user_posts() function.

How can I re-order the items based on this number? Highest to lowest?

The user post count is not part of the $users array :(

            // order contributors
            $args = array(
                'role' => contributors,
                'orderby' => 'post_count',
                'order' => 'ASC',
                'fields' => 'all'
            );

            // The Query
            $user_query = new WP_User_Query( $args );
            $users = $user_query->get_results();

            echo '<ul>';
            $i = 0;
            foreach ( $users as $user ) {

                $post_count = count_user_posts( $user->id );

                if ( count_user_posts( $user->id ) >= 1 ) {
                    echo '<li class="ws-sort" data-sort="' . $post_count . '"><a href="' . site_url() . '/author/' . $user->user_nicename . '">' . $user->display_name . '</li>';
                    if (++$i == 8) break;
                }
            }
            echo '</ul>';
wbdlc
  • 1,070
  • 1
  • 12
  • 34

1 Answers1

0

You can use usort with a custom function:

usort($users, function(&$a,&$b) {
    if (!isset($a->_post_count)) $a->_post_count = count_user_posts( $a->id );
    if (!isset($b->_post_count)) $b->_post_count = count_user_posts( $b->id );
    return  $a->_post_count < $b->_post_count;
});

And you can also use _post_count in the other foreach, since the sorting modified each element ( $a and $b are passed by reference )

darioguarascio
  • 1,077
  • 11
  • 15
  • This looks interesting, I am a bit confused by the placement of the above in the context of my for loop? – wbdlc Mar 26 '15 at 15:38
  • just after you do `$users = $user_query->get_results();` – darioguarascio Mar 26 '15 at 15:38
  • Merlin's beard! That looks to have, excuse the pun sorted the issue. Thank you and appreciated. – wbdlc Mar 26 '15 at 15:42
  • With pleasure you have answered my question. I wanted to ask also, as we have now filtered by the post post_count, is it possible to then sort that result by another sort condition? So post_count, then alphabetical? Or can you only have one sort order? Thank you. – wbdlc Mar 26 '15 at 15:48
  • with a custom function, the sorting condition can be whatever you want, in this case i used `$a->_post_count < $b->_post_count` but can be, for example, `$a->_post_count < $b->_post_coun && $a->username`. Just find the proper expression to return the order you need – darioguarascio Mar 26 '15 at 15:50