We are introducing a “featured author” area on our site and would like to display the most recent articles by a select group of authors. However, we only want a maximum of one post per author to display. So an author could potentially have posted 5 times since another author had posted, but regardless only one of their posts should appear. Currently this is the code I’ve got:
<?php
$args = array(
'showposts' => 5,
'author' => "6800,3845,1720,7045,4949"
);
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) : $the_query->the_post();
?>
// DISPLAYING STUFF
<?php endwhile; wp_reset_query(); ?>
One potential solution I have considered is querying more posts and setting up an array, then checking the array each time to see if an author is already in it. If they are, it would continue to the next row. But an obvious issue with this would be that I may potentially end up having to pull back 100’s of posts if a particular “featured author” hadn’t wrote for a while.
I’m still fairly new to PHP/MySQL and a solution is probably starring me in the face. Appreciate any assistance.
You need to
GROUP BY
the author ID, which is going to require a filter onposts_groupby
. The Codex page for that filter is non-existent but it works likeposts_join
. Something like…Use your own values in
$args
of course.that will effect any other query on the page that runs after this block of code. You might want to remove the filter after you are done.
Another approach could be to use a function that loops through
get_posts
and prints the result.Check this Q&A: When should you use WP_Query vs query_posts() vs get_posts()?
And then use it in any theme template:
<?php wpse_78117_print_authors_last_post(); ?>
.I had this problem for only wanting one post per author to put into a slider, and I resolved it like this: