I was trying to redirect my homepage to random blog post in WordPress.
My aim is to redirect my viewers to random blog posts whenever they enter into my website. I couldn't find a proper solution, can anyone help me?
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityIf you don't want to use a plugin. You could put the re-direct directly into your .htaccess (on an apache server):
Place this code at the bottom of the .htaccess file:
redirect 301 / http://www.example.com/your-post-slug
make sure to change the url to the full url of your blog post.
If you don't have access to your .htaccess you could also do this in your cPanel (or other hosting control panel if you have one)
You can use template_redirect
hook for that:
function my_page_template_redirect() {
if ( is_home() ) { // change to is_frontpage(), if you use static page as front page
$posts = get_posts( array(
'post_type' => 'post',
'orderby' => 'rand',
'numberposts' => 1
) );
if ( ! empty( $posts ) ) {
wp_redirect( get_permalink( $posts[0]->ID) );
die;
}
}
}
add_action( 'template_redirect', 'my_page_template_redirect' );
The quickest way to achieve this is to install the Redirect URL to Post plugin.
Via the query parameter, you can configure the homepage to load your latest post or a random one.
For example, your new homepage URL would be http://www.example.com/?redirect_to=random
You would likely need to change your home and site URL via WordPress settings. You can read more about this here.