任何问题请联系WX:uu16853

买模板送网站采集器 让你轻松放开双手运营网站!

购买更多有优惠!

WordPress搜索结果只有一篇文章时自动跳转到文章

当读者通过WordPress自身的搜索功能来搜索文章时,如果返回的结果只有一篇文章,我们可以直接让它跳转到这篇文章,提高用户体验。

实现的方法很简单,只需要在你主题的 functions.php 文件中添加下面的代码:

1
2
3
4
5
6
7
8
9
10
add_action('template_redirect', 'redirect_single_post');
function redirect_single_post() {
    if (is_search()) {
        global $wp_query;
        if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
            exit;
        }
    }
}

add_action(‘template_redirect’, ‘redirect_single_post’);
function redirect_single_post() {
if (is_search()) {
global $wp_query;
if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) {
wp_redirect( get_permalink( $wp_query->posts[‘0’]->ID ) );
exit;
}
}
}

参考资料:http://www.paulund.co.uk/redirect-search-results-return-one-post

100% Secure Checkout

PayPal / MasterCard / Visa