How to retrieve random posts from Wordpress

Posted on 03.10.17   PHP Wordpress






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(); 
    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

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

How to debug a non starting application with ProcMon

Change Resize Mode for all VMs in RoyalTS 4

Finding the source for locked AD account from Event Viewer log on Domain controller

Telnet alternative to check if port is open on host