How to display random posts in WordPress

A simple function to fetch 10 random posts in WordPress

Let's create a function and add it to functions.php

Step 1: arguments

Let's create an array named $args and add the arguments to it.

The post_type can be a post, a page or any other custom post type.

The orderby argument matters because it sets the order we want, here random.

orderby can also be title, name, ID, slug, etc.

With the posts_per_page argument, you decide how many posts you want to fetch.

$args = array(
    'post_type'      => 'post',
    'orderby'        => 'rand',
    'posts_per_page' => 10,
    );
...

Step 2: Wp_Query

Let's create a wp_query instance and pass $args to it

...
$query = new WP_Query( $args );
...

Step 3: fetch the posts

Let's check whether the $query variable contains any posts and, if so, store them with some HTML markup in a PHP string.

We'll also add an else branch for when there are no posts to fetch. In that case, we can simply display a message saying there are no posts to show.

...
if ( $query->have_posts() ) {
    $rand_posts .= '<section>';
        while ( $query->have_posts() ) {
            $query->the_post();
            $rand_posts .= '<a href="'. get_permalink() .'">'. get_the_title() .'</a>';
        }
    $rand_posts .= '</section>';
    wp_reset_postdata();
} else {
    $rand_posts .= '<p>Pas d\'articles</p>';
}
...

Note that wp_reset_postdata() is inside the if condition.

After the loop, we need to call wp_reset_postdata() to restore the global $post to the current post of the main query.

Step 4: function & shortcode

The final code

function my_random_posts() {

    $args = array(
        'post_type'      => 'post',
        'orderby'        => 'rand',
        'posts_per_page' => 10,
        );

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) {
        $rand_posts .= '<section>';
            while ( $query->have_posts() ) {
                $query->the_post();
                $rand_posts .= '<a href="'. get_permalink() .'">'. get_the_title() .'</a>';
            }
        $rand_posts .= '</section>';
        wp_reset_postdata();
    } else {
        $rand_posts .= '<p>Nothing to show</p>';
    }

    return $rand_posts;
}

add_shortcode('my-random-posts','my_random_posts');
add_filter('widget_text', 'do_shortcode');

You can simply call the function above with the shortcode, and it will display 10 random posts.

With do_shortcode, you can run the shortcode inside a widget.

Have a web project in mind?

Website design, e-commerce or SEO: our web agency in Paris, Besançon and Normandy can help.

Free quote

Related articles