1

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?

1

If 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)

2
  • 1
    And how is that a random post? – Krzysiek Dróżdż Feb 13 '19 at 15:36
  • Ah. I read it as random as in he wasn't sure what one he was going to direct them to (or he didn't want to specify to the general which). I see in the 2nd pp OP pluralized – rudtek Feb 13 '19 at 15:49
1

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' );
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.