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