Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

ok so i have this:

    $args=array(
            'orderby' => 'rand',
            'order'    => 'DESC',
            'posts_per_page' => 1,
            'offset' => $offset,
    );
$q = new WP_Query($args);
if ($q->have_posts()) {}

what im looking for is to Randomly show one of the last 3 posts:

SELECT * FROM 
(SELECT * FROM `wp_posts` WHERE `post_type` = 'post' ORDER BY post_date DESC LIMIT 3) 
AS temptable ORDER BY RAND() LIMIT 1
share|improve this question
    
If you know your MYSQL queries, you could just use them with $wbdb. codex.wordpress.org/Class_Reference/wpdb. Other wise you will need to query the first 3 posts first and then maybe put them in a array and sort the array. –  gdaniel Feb 20 at 22:28

1 Answer 1

$args=array(
            'orderby' => 'rand',
            'order'    => 'DESC',
            'posts_per_page' => 3,
            'offset' => $offset,
    );
$q = new WP_Query($args);


if($q->post_count>0){
    $random_post = $q->posts[mt_rand(0,2)];
}

also, just a little note, ORDER BY RAND() is pretty bad for performance

share|improve this answer
    
"...ORDER BY RAND() is pretty bad for performance" - can you please pose a link to support your argument? –  Mayeenul Islam Feb 21 at 6:35
    
@MayeenulIslam honestly, I can't support my point personally. I haven't done any benchmark regarding this. When I studied MYSQL and I heard a lot of negative opinions towards that. What I can provide to you is googling "order by rand mysql performance". –  Jesse Feb 21 at 11:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.