Random post functionality usually applied when you give your readers something new and maybe more advanced way to browse your site. The random post button will redirect your readers to a post throughout the entire website randomly. Whenever your readers will click that button they will be redirected to a random post from your entire website.
There are two possibilities of adding a random post button in your blog, either you can use a WordPress plugin or simply follow this post.
One of the most convenient way of adding the random post button in your blog is to follow the steps below:
1. Open up functions.php and add the following code at the bottom of it:
add_action('init','random_add_rewrite');
function random_add_rewrite() {
global $wp;
$wp->add_query_var('random');
add_rewrite_rule('random/?$', 'index.php?random=1', 'top');
}
add_action('template_redirect','random_template');
function random_template() {
if (get_query_var('random') == 1) {
$posts = get_posts('post_type=post&orderby=rand&numberposts=1');
foreach($posts as $post) {
$link = get_permalink($post);
}
wp_redirect($link,307);
exit;
}
}
#Snippet Credits: wpbeginner.com
2. Now, we need to create some HTML documents for the button and some CSS codes to give a pretty good look to it. Here we've created a button with complete CSS and HTML codes for our readers.
HTML:
Looking at the following html code use the permalink as https://www.yourdomain/index.php?random=1 and by going to Appearance > Widgets simply drag a text widget either in sidebar or in footer then add this code in that text widget.
<a href="https://softstribe.com/index.php?random=1">my button</a>
CSS:
Add the following CSS code in your style.css file:
.randbutton {
-moz-box-shadow:inset 0px 16px 16px -11px #fce2c1;
-webkit-box-shadow:inset 0px 16px 16px -11px #fce2c1;
box-shadow:inset 0px 16px 16px -11px #fce2c1;
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffc477), color-stop(1, #fb9e25) );
background:-moz-linear-gradient( center top, #ffc477 5%, #fb9e25 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc477', endColorstr='#fb9e25');
background-color:#ffc477;
-moz-border-radius:13px;
-webkit-border-radius:13px;
border-radius:13px;
border:2px solid #eeb44f;
display:inline-block;
color:#fff;
font-family:arial;
font-size:19px;
font-weight:bold;
padding:6px 24px;
text-decoration:none;
text-shadow:1px 0px 0px #cc9f52;
}.randbutton:hover {
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #fb9e25), color-stop(1, #ffc477) );
background:-moz-linear-gradient( center top, #fb9e25 5%, #ffc477 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fb9e25', endColorstr='#ffc477');
background-color:#fb9e25;
}.randbutton:active {
position:relative;
top:1px;
}
That's it! You have successfully created a new service for your readers. Hope they will be happy...