[wp-hackers] show 2 random posts from the last 20 posts from the Featured category

Haluk Karamete halukkaramete at gmail.com
Thu Feb 21 21:51:29 UTC 2013


When you want to show 2 random posts from the last 20 posts from the
Featured category, what's the best way to handle it?

When I go,

$args = array(
   'category_name' => 'featured',	
   'posts_per_page' => 2),

it pulls the last 2 posts from the featured cat. Obviously no
randomness can be achieved as such. It's the same as asking gimme the
last 2 posts from featured.

If I go

$args = array(
   'category_name' => 'featured',	
   'posts_per_page' => 2,
   'orderby' => 'rand'),

then I get the two 2 random posts. but then, recent'ness goes out the
window. I may be randomly picking featured posts that are as old as
the website is.

For a moment, I thought the following would have worked.

$args = array(
   'category_name' => 'featured',	
   'posts_per_page' => 20,
   'orderby' => 'date rand'    //notice the double order by here
);   // inspired by the
http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
codex entry.

I thought, this would have first picked the last 20 posts, and then
randomly shuffle the order and then return the results. If that were
to work, I would have exited the while loop at iteration 2 achieving
my goal.
But that too fails. It totally ignores the second aspect, the 'rand'
that is. and you always get the  recent 20 in the most recent to least
recent order.

So, how do you achieve that original goal which is "show 2 random
posts from the last 20 posts from the Featured category"?


More information about the wp-hackers mailing list