get random posts wordpress

To fetch random posts in WordPress, you can use the following code:

$args = array(
    'orderby' => 'rand',
    'posts_per_page' => 1
);

$random_query = new WP_Query( $args );

if ( $random_query->have_posts() ) {
    while ( $random_query->have_posts() ) {
        $random_query->the_post();
        // Your code to display the random post
    }
} else {
    // No posts found
}

wp_reset_postdata();

Here's an explanation of each step:

  1. Create an array of arguments including 'orderby' => 'rand' to fetch posts randomly and 'posts_per_page' => 1 to limit the result to one post.
  2. Initialize a new instance of WP_Query with the arguments.
  3. Check if the query has any posts.
  4. If posts are found, loop through each post using while and the_post() to set up the post data.
  5. Inside the loop, you can write the code to display the random post as per your requirements.
  6. After the loop, reset the post data using wp_reset_postdata() to restore the global post data to its original state.