How to order posts in wp_query by the user role (2 roles in array)

I’m using the following code from this answer:
How can I get the last posts by user role?

<?php
$friends = get_users( array( 'role' => 'friends' ) );
$friend_ids = array();

foreach( $friends as $friend ) 
    $friend_ids[] = $friend->ID;

$news = new WP_Query( array( 'author' => implode( ',', $friend_ids ), 'post_type' => 'news', 'paged' => get_query_var('paged') ) ); ?>

I’ve added another WP role to the array so it grabs both. For example:

Read More
$friends = get_users( array( 'role' => 'friends, enemies' ) );

Is it possible to now order the posts somehow by the role? so it displays all the friends first, followed by all the enemies etc. At the moment, it lists them all mumbo jumbo as expected.

EDIT: sorry, probably shouldn’t have set up another question, not sure why I did that. Is it possible to do this without using custom fields?

The problem I’ve found with custom fields is that If a user changed roles (due to membership levels) then the posts would not be ordered correctly until the post (from the author who changed) was saved with it’s new custom field value.

Related posts

Leave a Reply

1 comment

  1. Its possible with an ugly custom query but to save your self a lot of time an easier solution would be to add a custom field to each post with the user role , then your query would be much smoother for example say you have a custom field named `u_role’ then your query should look like this:

    $news = new WP_Query( array(
        'author' => implode( ',', $friend_ids ),
        'post_type' => 'news', 
        'paged' => get_query_var('paged'),
        'meta_key' => 'u_role',
        'orderby' => 'meta_value', 
        'order' => 'DESC') );