2

I'm using the code below from another answer to query posts from 1 custom role, eg "friends". I thought I could just comma separate the roles to list posts from more than one role, but this didn't work. Is there another way I can write it? I've tried 'role' => 'friends', 'enemies' and 'role' => 'friends, enemies' but I guess get_users only supports one 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') ) ); ?>

2 Answers 2

3

Just do the get_users() twice and merge the results:

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

$friends_n_foe = array_merge($friends, $enemies);

$IDs = array();

foreach( $friends_n_foe as $person ) {
    $IDs[] = $person->ID;
}

$news = new WP_Query( array( 'author' => implode( ',', $IDs ), 'post_type' => 'news', 'paged' => get_query_var('paged') ) );
?>
1
  • Thanks Brady, that ones definitely going in the tool belt
    – Andrew
    Jul 16, 2011 at 10:59
1

Below is function to get user ids for roles, from http://sltaylor.co.uk/blog/get-wordpress-users-by-role/

function getUsersByRole( $roles ) {  
    global $wpdb;  
    if ( ! is_array( $roles ) ) {  
        $roles = explode( ",", $roles );  
        array_walk( $roles, 'trim' );  
    }  
    $sql = ' 
        SELECT  ID, display_name 
        FROM        ' . $wpdb->users . ' INNER JOIN ' . $wpdb->usermeta . ' 
        ON      ' . $wpdb->users . '.ID              =       ' . $wpdb->usermeta . '.user_id 
        WHERE   ' . $wpdb->usermeta . '.meta_key     =       \'' . $wpdb->prefix . 'capabilities\' 
        AND     ( 
    ';  
    $i = 1;  
    foreach ( $roles as $role ) {  
        $sql .= ' ' . $wpdb->usermeta . '.meta_value LIKE    \'%"' . $role . '"%\' ';  
        if ( $i < count( $roles ) ) $sql .= ' OR ';  
        $i++;  
    }  
    $sql .= ' ) ';  
    $sql .= ' ORDER BY display_name ';  
    $userIDs = $wpdb->get_col( $sql );  
    return $userIDs;  
}  

I should work... may be you have syntax error...

See in below page.. Show Posts From Several Authors http://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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