WordPress 搜索结果只有一篇时自动定向到文章

要实现这样的功能,有两个方法:

一、添加自定义 HOOK

将下面的代码添加到主题中 functions.php 文件里:

add_action('template_redirect', 'wj_redirect_single_post');
function wj_redirect_single_post() {
if (is_search()) {
global $wp_query;
if ($wp_query->post_count == 1) {
wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
}
}
}

二、直接修改搜索模板文件(不推荐)

在 loop 循环里面添加以下代码:

if (is_search()) {
global $wp_query;
if ($wp_query->post_count == 1) {
wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
}
}
(0)

相关推荐