How can I redirect my website's homepage to a random blog post?

admin2025-06-03  2

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?

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?

Share Improve this question edited Feb 13, 2019 at 15:35 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Feb 13, 2019 at 15:03 Vignesh RSVignesh RS 111 bronze badge
Add a comment  | 

3 Answers 3

Reset to default 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/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/?redirect_to=random

You would likely need to change your home and site URL via WordPress settings. You can read more about this here.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748911949a314751.html

最新回复(0)