Im looking to order posts by the users role…
I currently have 2 user roles (intending to create more), and they are “Premium User” and “User”, and some poss created by “Admin”
All of these posts are on one page, and i would like all the posts that are written by the “Premium User” at the top, then the rest underneath.
I have currently accomplished this with 2 separate loops, however, as the site grows there will be need for pagination to be added, and with 2 separate loops, this isnt going to work.
Any help appreciated!
Thanks,
This one’s a little difficult, as there’s no default user role meta key or post data. The only thing we got is the user ID.
// Get the posts
$posts_by_author_ID = get_posts( array(
'post_type' => 'post'
,'post_status' => 'publish'
,'orderby' => 'post_author'
,'order' => 'DESC'
) );
foreach ( $posts_by_author_ID as $post )
{
static $user;
$new_user = get_user_by( 'id', $post->post_author );
// Let's save some queries
if (
isset ( $user )
AND $user->ID === $new_user->ID
)
continue;
$user = $new_user;
foreach ( $user->roles as $role )
{
$posts_by_author_role[ $role ] = array(
'user' => $user
,'post' => $post
);
}
}
// Sort by key a.k.a. role
ksort( $posts_by_author_ID );
echo '<pre>'; // Only for debugging/developing - should get deleted when done
foreach ( $posts_by_author_ID as $role => $data )
{
list( $user, $post ) = $data;
// Now we can output our data
// The user data is saved inside $user
// The actual post data is saved inside $data
// The following is only for debugging/developing - should get deleted when done
var_export( $user, false );
var_export( $post, false );
}
echo '</pre>'; // Only for debugging/developing - should get deleted when done