Display Random Posts In WordPress Without Plugin

0
1545
views


When your website become popular or start to get a good traffic, it’s time to retain your blog visitors by providing more interesting content and articles to read. How can you do that ? the answer is displaying random posts in WordPress! This tutorial on how to display random posts in WordPress without a plugin will give you two advantages : Clean fast loading Code and Less use of database requests, which will have a good impact on your WordPress load speed.

How to Display Random Posts In WordPress Without Plugin

1- Display Random Posts in Any Part of Your WordPress Blog

You can use this small code in any part of your theme to display random posts :

<div>
<h2>Other Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1);
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>
</div>

‘numberposts’ => 5, : with this code we will display 5 random posts, so you can change this value.

2- Display Random Posts in WordPress with Excerpt

<div>
<h2>Random Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1);
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><p><?php the_excerpt(); ?></p></li>
<?php endforeach; ?>
</ul>
</div>

After adding one of this codes, we will have to style them. To do that, open the style.css of your theme and add this code :

.random-posts {
margin: 10px 0;
}
.random-posts p{
font-size:13px;
}
.random-posts h2{
font-size: 16px;
font-weight: bold;
}
.random posts ul {
list-style: square;
margin: 10px 0;
}
.random posts ul li {
padding: 3px 0;
border-bottom: 1px dashed #ccc;
}
.random posts ul li a {
font-size: 14px;
text-decoration: none;
}

Note that can use different colors, size..etc to suit your theme style design.

That’s all ;) See you soon for another quick WordPress tutorials here on SeoDesign.

You can also read our previous article : How to add WordPress pagination without plugin.

If you found this article useful for you please share it with your friends on social networks such google+ and facebook! You can always follow us on Facebook and add us to your Google+ circles.


hello all, im marcella, 27 years old from Mexico, i work and continue my studies in web designer and web development, wish all the best to the website and it's nice to be with you here.
SHARE

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.