Web Development

Get Random Post in WordPress

Here is the quick code snippet to get the random post from wordpress database. This can be usefult if you create “Random Post” link in your website and get random post for your readers.

I will get this done very quick here with just code block. I will explain the same task with two different ways:

Method 1: Using get_posts()

[cc lang=”php”]
$args = array(
‘numberposts’ => 1,
‘orderby’ => ‘rand’
);

$random_post = get_posts ( $args );
// Your random post is ready now.
[/cc]

Method 2: Using WP_Query Object

[cc lang=”php”]
$args = array(
‘posts_per_page’ => 1,
‘orderby’ => ‘rand’
);

$random_post = new WP_Query ( $args );

while ( $random_post->have_posts () )
{
// traditional WordPress Look
}
[/cc]

There can be other severals ways to get this done, but I have explained which comes first to mind while writing this.

Subscribe to get latest updated right into your inbox, Follow us on twitter and Like us on facebook.

Shares:

Leave a Reply

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