我正在尝试将我的WordPress主页自动重定向到最新的文章。 目前我使用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' );
现在,如果我发布第2条,我希望主页自动连接到第2条而不调整functions.php。
我希望没有用户可以看到www.example.com
但只有文章,因此访问该页面时始终会重定向到最新文章。
然而:
我希望仍然可以访问www.example.com/article1
(通过手动输入网址),即使已经有www.example.com/article2
。
我怎样才能实现这个目标?
答案 0 :(得分:0)
答案在Get the ID of the latest post:做一个简单的查询来获取一个帖子(默认按最新排序),然后抓住它的固定链接和重定向。
Don't put this type of code in functions.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;
}
答案 1 :(得分:0)
朋友的解决方案: 使用以下内容替换模板文件夹中的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; ?>
感谢您帮助我