Blog / WordPress/ How to Display Random Posts in WordPress (Site-Wide & Same Category)

How to Display Random Posts in WordPress (Site-Wide & Same Category)

In a previous tutorial, you learned how to display recent posts, popular posts, and posts from specific categories. Sometimes, you may need more display options, such as showing random posts. How can you display random posts from your entire site, or random posts from the same category as the current post?

This guide explains two methods to achieve these functions.

Site-Wide Random Posts

The following code retrieves published posts from your entire site and displays a specified number of random post titles with links.

<?php
// Set query arguments
$args = array(
    'numberposts' => 5,      // Number of posts to display
    'orderby'     => 'rand', // Order by random
    'post_status' => 'publish' // Get only published posts
);

// Get posts
$rand_posts = get_posts( $args );

// Loop through and display posts
foreach( $rand_posts as $post ) :
    setup_postdata( $post ); // Setup global post data
?>
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php
endforeach;
wp_reset_postdata(); // Reset post data
?>

Code Explanation:

  • Uses the get_posts() function to retrieve posts.
  • The key parameter is 'orderby' => 'rand' for random ordering.
  • The loop uses setup_postdata() and wp_reset_postdata() to ensure template tags like the_permalink() work correctly.

Random Posts from the Same Category

This code retrieves random posts from the same category as the current post.

<?php
// Get the current post's categories
$categories = get_the_category();
if ( ! empty( $categories ) ) {
    $category_id = $categories[0]->term_id; // Get the first category ID

    // Set query arguments
    $args = array(
        'cat'            => $category_id, // Specify category ID
        'posts_per_page' => 8,            // Show 8 posts
        'orderby'        => 'rand',       // Random order
        'post_status'    => 'publish'     // Published posts only
    );

    // Create a new query
    $random_query = new WP_Query( $args );

    // Loop through posts
    if ( $random_query->have_posts() ) :
        while ( $random_query->have_posts() ) : $random_query->the_post();
    ?>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    <?php
        endwhile;
    else :
        echo 'No other posts found in this category.';
    endif;

    // Reset post data
    wp_reset_postdata();
}
?>

Code Explanation & Corrections:

  • Uses the standard posts_per_page parameter instead of the deprecated showposts.
  • Includes error handling: checks if the post has a category to avoid errors.
  • Simplifies logic by using the first category ID.
  • Uses WP_Query for more flexible querying.
  • Checks if posts exist and provides a user-friendly message if none are found.

How to Use

Place either code snippet into your WordPress theme template file (e.g., single.php, sidebar.php) where you want the random posts to appear.

You can easily control the number of posts displayed by modifying the numberposts or posts_per_page parameter.

Post a Comment

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