The code you have posted above does not represent any kind of database performance issue.
There is ‘orderby’ => ‘rand’ what is highly not optimal for database.
It does not represent any kind of database performance issue within a WordPress site.
I’d be interested to know how using RAND affects performance.
I don’t know. I’m not a programmer.
I was told that getting posts from database using “order by rand” is not optimal because everytime it creates temporary table. Whatever.
Can someone tell me how to show 10 random posts without using the method that I’ve shown above?
Thanks in advance for your help.
So you want random posts without using random as a parameter? That’s not possible.
I want random posts without “orderby rand()”.
In the link that I posted above there was a solution that in author’s opinion should work.
I really don’t see a performance issue with using “order by RAND”. You could always test out the theory using pingdom.com to check the page load speed to see if there is a massive slowdown in load speed when you’ve implemented RAND.
@aassddff: Your original example code is the most straightforward for getting random posts. Depending on the number of posts your blog has, you’ll likely not notice the difference between that approach and a more efficient approach.
If you want a more efficient approach, however, here’s an variation based on what you had above:
<ul>
<?php
global $wpdb;
$post_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type = 'post';" );
shuffle( $post_ids );
$rand_posts = get_posts( array( 'include' => array_slice( $post_ids, 0, 10 ) ) );
foreach ( $rand_posts as $p ) : ?>
<li><a href="<?php echo get_permalink( $p->ID ); ?>"><?php echo get_the_title( $p->ID ); ?></a></li>
<?php endforeach; ?>
</ul>
This approach obtains all valid post IDs from the database, randomizes them in PHP, and selects 10 for use to query for actual posts.
@coffee2code:
Thanks for your help, but this solution works like my previous. When I put this code on my website it’s not loading at all. Just blank screen.
Mine problem is that I’ve got WordPress with lost of posts (>100k) and random kills execution in php (I think).
Is this possible to make a loop which choose a number between 1 and numer_of_my_posts and receive a post (link to post actually) with chosen id?
No need to check whether this id is correct.
No need to check if we’ve already choose this id.
That’s all I’m asking for. It would be great if this would be possible.
And thanks for your help anyway!