Random WordPress Comic

Have you ever wanted to have a random comic button on your website?

For example, you could include a random post link in one of your updates or create a button in your WordPress site’s sidebar. Perhaps your theme offers this function but this will allow you to put it wherever you wish.

This can be accomplished in two steps:

1. Add the following code to your theme’s Functions file…

//random wordpress post
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;
}
}

2. This link (http://yourdomain.com/index.php?random=1) will take you to a random post when you click on it.

Sources:
http://wpguy.com/articles/how-to-make-a-random-post-button/
http://www.wpbeginner.com/wp-tutorials/how-to-redirect-users-to-a-random-post-in-wordpress/

Comments are closed.