1

I have created a custom loop to show only admin posts, but now I would like it to display posts from both admins and contributors.

Any help is GREATLY appreciated!

Here is what I have so far:

echo "<div class='post_wrap " . $infinite . "'>";
$users_query = new WP_User_Query( array( 
                                        'role' =>  'administrator',

                                        'orderby' => 'display_name'
                                        ) );
$site_admins = array();
$results = $users_query->get_results();
foreach($results as $user) {
    $site_admins[] = $user->ID;
}

$admins = implode(',',$site_admins);
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; 
query_posts(array('post_type' => 'post', 'author' => $admins, 'paged' => $paged, 'posts_per_page' => 10));
while (have_posts()) : the_post();
2
// Query user data on admins
$administrators = new WP_User_Query( array( 'role' =>  'administrator' ) );

// Query user data on contributors
$contributors = new WP_User_Query( array( 'role' =>  'contributor' ) );

// Save admin IDs
foreach( $administrators->results as $u )
    $user_ids[] = $u->ID;

// Save contributor IDs
foreach( $contributors->results as $u )
    $user_ids[] = $u->ID;

// Little cleanup
unset( $u, $administrators, $contributors );

// Save paged value (for paginating results)
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; 

// query_posts()
query_posts(
    array( 
        'post_type' => 'post',
        'author__in' => $user_ids,
        'paged' => $paged
    )
);

// If the query has data
if( have_posts() ) :

    // Post loop
    while ( have_posts() ) : 

        // Setup post data
        the_post();
        ?>

        <!-- Do HTML markup and template tags here, eg. the_content(), the_title() etc.. -->
        <h1><?php the_title(); ?></h1>

        <?php
    endwhile;

// End "If the query has data"
endif;

@1fixdotio : WP_User_Query returns an object of each user. WP_Query takes user ids only so we have to extract the ids from the user objects. I think that is the only mistake there.

2
  • YOU ARE A GENIUS! Thank you so much. This worked perfectly :D – Kylie Lakevold Cawte Feb 2 '14 at 20:35
  • Cleaned the code up for you somewhat, should hopefully make for easier reading. Note, query_posts should be fine for use inside a page template or selective uses where the main query won't be used otherwise, else WP_Query would be more appropriate. – t31os Feb 3 '14 at 18:31

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.