简体   繁体   English

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

[英]Redirect WordPress homepage to newest Article

I am trying to redirect my WordPress homepage to the newest article automatically. 我正在尝试自动将WordPress主页重定向到最新文章。 At the moment I use a redirect suggested by Spencer Cameron 目前,我使用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. 现在,如果我发布第2条,我希望主页能够自动连接到第2条,而无需我调整functions.php。

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. 我希望没有用户看到www.example.com而只有文章,所以在访问页面时总会重定向到最新的文章。

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 . 我想仍然可以访问www.example.com/article1 (通过手动键入url),即使已经存在www.example.com/article2

How could I achieve that goal? 我怎样才能实现这个目标?

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. 答案是在获取最新帖子的ID中 :做一个简单的查询即可获取一篇帖子(默认情况下最新排序),然后获取其固定链接并重定向。

Don't put this type of code in functions.php , create your own mini-plugins to do it. 不要将这种类型的代码放在functions.php中 ,而要创建自己的微型插件。 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;
}

A solution from a friend: Replace index.php in the template folder with the following: 朋友的解决方案:将模板文件夹中的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; ?>

Thanks for helping me out 谢谢你的协助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM