Home / Widgets / Display Random Posts
Duplicate Snippet

Embed Snippet on Your Site

Display Random Posts

Show random posts anywhere on your site.

90+
Code Preview
php
<?php
$number_of_posts = 5; // Change this to the number of random posts you want to display.
$title = 'You might also like:'; // This is the title that will be displayed above the list of posts.
$current_post_id = get_the_ID();
$args = array(
	'post_type'      => 'post',
	'orderby'        => 'rand',
	'posts_per_page' => $number_of_posts,
	'post__not_in'   => array( $current_post_id ),
);
$random_posts = new WP_Query( $args );
if ( $random_posts->have_posts() ) {
	echo '<h3>' . esc_html( $title ) . '</h3>';
	echo '<ul>';
	while ( $random_posts->have_posts() ) {
		$random_posts->the_post();
		echo '<li><a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</a></li>';
	}
	echo '</ul>';
}
wp_reset_postdata();

Comments

Add a Comment