Redirect to random post
-
How do I make a page redirect to a random post? It worked on my blog before, but now for some reason it’s stopped working.
For the page I want to redirect from, I’ve put this for the redirect URL:
https://www.myblogname.com/index.php?random=1
In functions.php, I’ve added:
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; } }
Despite my two actions, the page just redirects to the latest post in my blog.
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- The topic ‘Redirect to random post’ is closed to new replies.