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

Get Linux distribution information from terminal


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


Oracle Universal Installer - Successfully completed with errors


Change Resize Mode for all VMs in RoyalTS 4


NiceHash hacked?




Leave a Reply

Your email address will not be published. Required fields are marked *