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?
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?
Share Improve this question edited Nov 18, 2015 at 15:52 user9447 1,7927 gold badges30 silver badges55 bronze badges asked Nov 18, 2015 at 14:50 ErikErik 1131 silver badge5 bronze badges 4- What if there's more or less than 8 authors? – Howdy_McGee ♦ Commented Nov 18, 2015 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 Commented Nov 18, 2015 at 15:04
- Any other suggestions? – Erik Commented Nov 18, 2015 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 ♦ Commented Nov 18, 2015 at 17:20
2 Answers
Reset to default 5I 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.
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' );