Learn to display random posts in any templates of WordPress by plugin and code.168

Display random posts

Display random post helps you to grasp more user attention as user will be able to view different post time to time. In this article, we are going to guide you can guide you to display random posts in WordPress

Why and where to display random post in WordPress

WordPress display post in chronological order from newest to oldest post which means viewers needs to search for an old post if they want to view it which is generally time-consuming.

There are two ways which can help you to encourage your viewers to view the old post. Firstly, you can link your new post with the old one (it may help you to increase your page views and improve your SEO). The next thing you can do is, display random posts in your sidebar.

Now, we are going to show you 2 different methods you can use to display random posts in your sidebar.

Method 1: Display random posts in WordPress with a plugin

In this method, we will guide you to display random posts in WordPress with a plugin. You may follow the steps below:

  1. Install and activate Advanced Random Posts Widget
  2. After activated, Go to: Appearance > Widgets. Click on ‘Random Posts’ under the list of available widget.
  3. Now, add this widget to a sidebar and click on ‘save’ button. Demo picture is given below:

(Note: if you are an experienced user you may browse the widget setting further

as it allows you to add custom HTML and CSS as well)

 

Method 2: Display random posts in WordPress using code

In this method, we will guide you to display random posts in WordPress using a code. You may follow the steps below:

  • Add the code below in your theme’s functions.php file or site-specific plugin:
function ib_rand_posts() {
$args = array(
'post_type' => 'post',
'orderby'   => 'rand',
'posts_per_page' => 10,
);

$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
$string .= '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$string .= '<li><a href="'. get_permalink() .'">'.
get_the_title() .'</a></li>';
}

$string .= '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
$string .= 'no posts found';
}

return $string;
}

add_shortcode('ib-random-posts','ib_rand_posts');
add_filter('widget_text', 'do_shortcode');

 

(note: this code creates function that displays 10 random posts, then it creates shortcode and it enables shortcodes to be executed inside WordPress widgets)

 

  • Now you can use
    shortcode [ib-random-posts] 

    to display text widget inside WordPress post, page or text widget.