将WordPress主页重定向到最新文章


Redirect WordPress homepage to newest Article

我正在尝试自动将我的WordPress主页重定向到最新文章。目前我使用斯宾塞卡梅隆建议的重定向

function redirect_homepage() {
    if( ! is_home() && ! is_front_page() )
        return;
    wp_redirect( 'http://homepage.com/article1', 301 );
    exit;
}
add_action( 'template_redirect', 'redirect_homepage' );
现在,如果我发布文章 2,

我希望主页自动连接到文章 2,而无需我调整功能.php。

我不希望用户看到www.example.com,而只看到文章,因此在访问页面时总是会重定向到最新文章。

然而:
我希望即使已经有www.example.com/article2,我也希望仍然有可能访问www.example.com/article1(通过手动输入 url)。

我怎样才能实现这个目标?

答案在获取最新帖子的 ID 中:执行一个简单的查询以获取一个帖子(默认按最新排序),然后获取其永久链接并重定向。

不要把这种类型的代码放在函数中.php,创建自己的迷你插件来做到这一点。如果您想禁用此功能,只需禁用插件,而不是编辑文件即可。

<?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;
}

来自朋友的解决方案:将模板文件夹中的 index.php 替换为以下内容:

<?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; ?>

谢谢你帮助我