Redirect WordPress homepage to newest Article

I am trying to redirect my WordPress homepage to the newest article automatically.
At the moment I use a redirect suggested by Spencer Cameron

function redirect_homepage() {
    if( ! is_home() && ! is_front_page() )
        return;

    wp_redirect( 'http://homepage.com/article1', 301 );
    exit;
}

add_action( 'template_redirect', 'redirect_homepage' );

Now if I post article 2 I want the homepage to automatically connect to article 2 without me adjusting the functions.php.

Read More

I want no user to see the www.example.com but only the article, so there is always a redirect to the newest article when visiting the page.

However:
I want to have the possibility to still access www.example.com/article1 (by manually typing the url) even if there is already www.example.com/article2.

How could I achieve that goal?

Related posts

Leave a Reply

2 comments

  1. The answer is in Get the ID of the latest post: do a simple query to get one post (ordered by latest by default), then grab its permalink and redirect.

    Don’t put this type of code in functions.php, create your own mini-plugins to do it. If you want to disable this, it’s just a matter of disabling a plugin, and not of editing a file.

    <?php
    /* Plugin Name: Redirect Homepage */
    
    add_action( 'template_redirect', 'redirect_homepage' );
    
    function redirect_homepage() 
    {
        if( ! is_home() && ! is_front_page() )
            return;
    
        // Adjust to the desired post type
        $latest = get_posts( "post_type=post&numberposts=1" );
        $permalink = get_permalink( $latest[0]->ID );
    
        wp_redirect( $permalink, 301 );
        exit;
    }
    
  2. A solution from a friend:
    Replace index.php in the template folder with the following:

    <?php global $query_string; query_posts($query_string.'&posts_per_page=1');  ?>
    <?php while ( have_posts() ) : the_post(); ?>
    <?php header('Location: '.get_permalink()); ?>
    <?php endwhile; ?>
    

    Thanks for helping me out