How to Display Random Posts in WordPress (Easy Tutorial)

16 hours ago, WordPress Tutorials, Views
Displaying random posts in WordPress

How to Display Random Posts in WordPress (Easy Tutorial)

Want to spice up your WordPress site and keep your visitors engaged? Displaying random posts is a fantastic way to showcase older content, encourage exploration, and keep your website fresh. This tutorial will guide you through several easy methods to achieve this, catering to different skill levels and preferences.

Why Display Random Posts?

Before diving into the how-to, let’s understand why you might want to display random posts on your WordPress website:

  • Increased Engagement: Random posts can pique visitors’ curiosity and encourage them to click on articles they might otherwise have missed.
  • Content Discovery: It helps bring older, high-quality content back into the spotlight, preventing it from getting buried in your archives.
  • Reduced Bounce Rate: By providing visitors with more options, you can keep them on your site longer and reduce the bounce rate.
  • Freshness Perception: Displaying different content each time someone visits gives the impression that your site is constantly updated and active.

Method 1: Using a WordPress Plugin

The easiest and most beginner-friendly way to display random posts is by using a WordPress plugin. Several plugins are available, but we’ll use “Display Random Posts” as an example. The steps are generally similar for most plugins of this type.

Installation and Activation

  1. Navigate to your WordPress dashboard.
  2. Go to “Plugins” > “Add New.”
  3. Search for “Display Random Posts.”
  4. Find the plugin (by WPBrigade), install, and activate it.

Configuring the Plugin

After activation, you’ll usually find the plugin settings under “Appearance” > “Widgets” or a dedicated settings page. The configuration options might include:

  • Number of Posts: The number of random posts to display.
  • Title: A title for the widget (e.g., “You Might Also Like,” “Random Reads”).
  • Display Options: Options to display the post title, excerpt, featured image, or date.
  • Exclusion Categories: The ability to exclude posts from specific categories.

Adding the Widget

  1. Go to “Appearance” > “Widgets.”
  2. Find the “Display Random Posts” widget.
  3. Drag and drop the widget to your desired sidebar or widget area.
  4. Configure the widget settings according to your preferences.
  5. Save the widget.

Method 2: Using a Code Snippet in your Theme’s functions.php File

For those comfortable with a little code, you can add a custom function to your theme’s `functions.php` file. This provides more control over the output and avoids relying on a plugin.

Important Warning

Before modifying your `functions.php` file, it’s crucial to back up your website. A small error in the code can break your site. Alternatively, use a code snippets plugin for safer implementation.

Adding the Code Snippet

Here’s a code snippet you can use. Remember to adjust the parameters to fit your needs.


function display_random_posts($num_posts = 5) {
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $num_posts,
        'orderby' => 'rand',
        'no_found_rows' => true
    );

    $random_query = new WP_Query($args);

    if ($random_query->have_posts()) {
        echo '<ul>';
        while ($random_query->have_posts()) {
            $random_query->the_post();
            echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        }
        echo '</ul>';
        wp_reset_postdata();
    } else {
        echo '<p>No posts found.</p>';
    }
}

Explanation of the Code

  • `function display_random_posts($num_posts = 5)`: Defines a function named `display_random_posts` that accepts an optional argument for the number of posts to display (defaulting to 5).
  • `$args = array(…)`: Creates an array of arguments for the `WP_Query` class.
  • `’post_type’ => ‘post’`: Specifies that we want to retrieve posts.
  • `’posts_per_page’ => $num_posts`: Sets the number of posts to retrieve.
  • `’orderby’ => ‘rand’`: Orders the posts randomly.
  • `’no_found_rows’ => true`: Improves performance by skipping the calculation of total posts.
  • `$random_query = new WP_Query($args)`: Creates a new instance of the `WP_Query` class using the defined arguments.
  • The `if` statement checks if there are any posts.
  • The `while` loop iterates through the retrieved posts.
  • `get_permalink()`: Retrieves the permalink of the current post.
  • `get_the_title()`: Retrieves the title of the current post.
  • `wp_reset_postdata()`: Resets the global post data after the loop.

Displaying the Random Posts

Now that you’ve added the function, you can display the random posts in your theme’s templates (e.g., `sidebar.php`, `footer.php`, single.php) by calling the function:


<?php display_random_posts(); ?>

You can also specify the number of posts to display:


<?php display_random_posts(3); ?>

Method 3: Using a Shortcode

A shortcode offers flexibility in displaying random posts within your content. We’ll modify the previous code snippet to create a shortcode.

Modified Code Snippet


function random_posts_shortcode($atts) {
    $atts = shortcode_atts(array(
        'num' => 5, // Default number of posts
    ), $atts);

    $num_posts = intval($atts['num']);

    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $num_posts,
        'orderby' => 'rand',
        'no_found_rows' => true
    );

    $random_query = new WP_Query($args);

    $output = '<ul>';
    if ($random_query->have_posts()) {
        while ($random_query->have_posts()) {
            $random_query->the_post();
            $output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        }
    } else {
        $output .= '<p>No posts found.</p>';
    }
    $output .= '</ul>';

    wp_reset_postdata();
    return $output;
}
add_shortcode('random_posts', 'random_posts_shortcode');

Explanation of the Changes

  • `function random_posts_shortcode($atts)`: Defines a function named `random_posts_shortcode` that accepts an array of attributes (`$atts`).
  • `$atts = shortcode_atts(…)`: Sets default values for the shortcode attributes.
  • `’num’ => 5`: Defines the default number of posts to display as 5.
  • `$num_posts = intval($atts[‘num’])`: Converts the ‘num’ attribute to an integer.
  • `add_shortcode(‘random_posts’, ‘random_posts_shortcode’)`: Registers the shortcode with WordPress, associating the tag `[random_posts]` with the `random_posts_shortcode` function.
  • The code now builds the output string and returns it for the shortcode to display.

Using the Shortcode

Now you can use the shortcode `[random_posts]` in your posts, pages, or widgets (if your widget area supports shortcodes). To display a specific number of posts, use the `num` attribute:


[random_posts num="3"]

This will display 3 random posts.

Customizing the Output

Regardless of the method you choose, you can customize the output further. For the plugin method, explore the plugin’s settings. For the code snippet and shortcode methods, you can modify the HTML within the functions to include featured images, excerpts, or other information.

For example, to add a featured image to the code snippet or shortcode, you could include the following code within the `while` loop:


<?php if ( has_post_thumbnail() ) : ?>
    <a href="<?php the_permalink(); ?>">
        <?php the_post_thumbnail( 'thumbnail' ); ?>
    </a>
<?php endif; ?>

This code checks if the post has a featured image and, if so, displays it as a thumbnail linked to the post.

Conclusion

Displaying random posts is a simple yet effective way to enhance your WordPress website. Whether you choose a plugin for ease of use, a code snippet for more control, or a shortcode for flexibility, you can easily implement this feature and improve user engagement. Remember to back up your website before making any code changes. Experiment with different configurations to find what works best for your site and content.