How to display a random article on your WordPress blog?

Ever this a blog where there was a button for you to click and instantly access a random article that same blog? Although this feature is not useful to many bloggers who write content regularly or are creating professional blogs to make money, the truth is it can be quite useful for other types of projects , such as blogs of humor, comic strips and other timeless subjects. When properly used , this feature can make the user experience of your blog and fun for your readers.




How to display a random article on your WordPress blog
Otto colleague developed a very cool function during WordCamp Louisville , which allows you to show precisely a random URL for your server, and use this opportunity to show random content for your readers. The famous blog of humor The Oatmeal uses a feature of these in your blog , for example :
When you click “Random” it shows a new article / cartoon completely randomly , keeping the prisoner user on the site and reading new posts one after the other . This concept when used in the most correct way, it is an excellent opportunity to keep their users engaged on your site.
This function uses a targeting 307 for temporary redirects, as they send the rules of Optimization for Search Engines . The objective of this redirection is that browsers do not cache the redirect results, as with a 302 redirect .
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;
       }
}
There are plugins to do this kind of stuff, but given the simplicity of the function, needless to you use a plugin to do this. Copy and paste the above code into the functions.php file of your template and / or use the code to create a “random ” button on their websites and blogs , for example.




LEAVE A REPLY

Please enter your comment!
Please enter your name here