1

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?

  • What if there's more or less than 8 authors? – Howdy_McGee Nov 18 '15 at 14:54
  • There is more than 100 authors on the site. I need to display only latest 8 products on the frontpage. 1 latest product per author. – Erik Nov 18 '15 at 15:04
  • Any other suggestions? – Erik Nov 18 '15 at 16:53
  • have you tried the current answer? If that doesn't work for you comment on it and explain why it didn't work. – Howdy_McGee Nov 18 '15 at 17:20
5

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.

  • Thanks, this looks like it could work. However how do I get this to apply just to my query above? Wouldn't this affect all queries? – Erik Nov 20 '15 at 16:37
  • 1
    remove_filter() after your query runs. – s_ha_dum Nov 20 '15 at 17:07

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.