Question

I want to show 8 recent products from multiple authors on the frontpage. Need to show 1 recent product per author.

Currently i'm using basic wp query to show recent 8 products.

$args = array (
'post_type'              => array( 'product' ),
'posts_per_page'         => '8',
'order'                  => 'DESC',
'orderby'                => 'date',
);

// The Query
$query = new WP_Query( $args );

What's the best way to achieve this?

Was it helpful?

Solution

I believe that you can achieve this effect by grouping the query by author ID, which will require a filter(mostly cribbed from the Codex):

function my_posts_groupby($groupby) {
    global $wpdb;
    $groupby = "{$wpdb->posts}.post_author";
    return $groupby;
}
add_filter( 'posts_groupby', 'my_posts_groupby' );

If you have less than 8 authors, however, this won't work. (You will get a number of results equal to your number of authors.) If that is the case you will need much more complicated logic and a much more complicated code.

OTHER TIPS

Anyone coming to this years after the fact and would like the code in full, rather than having to piece this together from comments and the accepted answer, here you go!

Declare the function that limits the post results to 1 per author. For me, this was in functions.php:

function one_per_author($groupby) {
    global $wpdb;
    $groupby = "{$wpdb->posts}.post_author";
    return $groupby;
}

Do NOT follow this with apply_filter as per the accepted answer - this would then apply to all loops.

Next run the loop you would like to filter, and call the apply and remove filters directly before and after it:

$args = array (
'post_type'              => array( 'product' ),
'posts_per_page'         => '8',
'order'                  => 'DESC',
'orderby'                => 'date',
);

add_filter( 'posts_groupby', 'one_per_author' );
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
   while ( $query->have_posts() ) : $query->the_post();
      // Do loop stuff
   endwhile;
endif;
remove_filter( 'posts_groupby', 'one_per_author' );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top