How to retrieve random posts from Wordpress

Posted on 03.10.17   PHP Wordpress

Revised:

 

 

 


Old:

This is just a quick solution I cooked up. Performance-wise it won’t be the best because it’s actually retrieving all posts, then shuffling the array and finally pick out 3 of them.

Here it is anyways:

function ShowRandomPosts() { 
    $get_random_posts = get_posts(); 
    shuffle($get_random_posts); 
    echo '<div style="padding:10px;">'; 
    echo '<h3>Random posts</h3>'; 
    for($i=0; $i<3; $i++) { 
        echo '<div>'; 
        echo '<a href="'.get_post_permalink($get_random_posts[$i]->ID).'" style="color:#fff;">'; 
        echo '<img src="'.get_the_post_thumbnail_url($get_random_posts[$i]->ID).'" style="max-width:100px;"><br>'; 
        echo '<h4>'.$get_random_posts[$i]->post_title.'</h4>'; 
        echo '</a>'; 
        echo '</div>'; 
    } 
    echo '</div>';
}

Note that the HTML and inline CSS is just an illustration so you would probably want to change that.

More on ITDB

Telnet alternative to check if port is open on host


Create a cmd alias/shortcut for issuing commands on remote computer


Turn off CTRL + ALT + DEL at login prompt Windows 10


Managing WiFi profiles in Windows 10


How to debug a non starting application with ProcMon