Yogesh Chauhan's Blog

How to display random posts in WordPress?

in WordPress on July 25, 2021

I have not included the CSS part so you’ll still need to design it the way you want.

Let’s create a function and add it to functions.php file in your theme.

Step 1: Arguments

Let’s create an array variable named as $args and add the arguments to it.

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

The orderby argument is important since that is the order we want for random posts.

You can have orderby as title, name, ID, slug, etc. and use the same function for many purposes.

With posts_per_page argument you can 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 an instance of WP_Query and pass the $args array.


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

Step 3: Fetch the posts

Let’s check if there are any posts in the $query variable and if so, save those posts with an HTML code in a PHP string.

Also, we will have an else condition too in case of no posts to fetch. In that case, we can just show some message that indicates that there are no posts to display.


...
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>';
}
...


Note that there is wp_reset_postdata() in the if condition.

Since we’re using a specific query, we are affecting the $post global but in the loop there is not much we can do.

So, after the loop we need to use wp_reset_postdata() to restore the $post global to the current post in the main query.


Step 4: Function and a shortcode

Let’s write the complete function by using the code chunks above.


function yc_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('yc-random-posts','yc_random_posts');
add_filter('widget_text', 'do_shortcode'); 


You can just call the function above using the shortcode [yc-random-posts], and it will display 10 random posts.

Using do_shortcode we can execute the shortcode inside a widget.


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Implicit and Explicit Joins in Oracle SQLSQL/MySQLShort-Circuit Evaluation in JavaScriptJavaScriptHow to change CSS with JavaScript?CSSHow SCSS (Sass) finds a module without a file extension?SCSSHow to create and store JSON objects in localStorage using JavaScript?JavaScriptHow to Draw a Text Image using JavaScript?JavaScript