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

Haluk Karamete halukkaramete at gmail.com
Thu Feb 21 22:05:21 UTC 2013


That would not not take from the last 20 recent featured ones though.

but anyway, with a little research, I think the following does the job.

shuffle( $my_query->posts );

Run this, right before the while loop abd whatever is in the posts
array ( last 20 featured posts for example ), get shuffled.
And then I exit at 2.



On Thu, Feb 21, 2013 at 1:56 PM, Kirk Wight <kwight at kwight.ca> wrote:
> Thinking out loud, you could query for the last twenty posts returned in
> random order, and pull the first two of off the results.
>
> On 21 February 2013 16:51, Haluk Karamete <halukkaramete at gmail.com> wrote:
>
>> 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"?
>> _______________________________________________
>> wp-hackers mailing list
>> wp-hackers at lists.automattic.com
>> http://lists.automattic.com/mailman/listinfo/wp-hackers
>>
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers


More information about the wp-hackers mailing list