最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

functions - How to redirect to post if search results only returns one post

programmeradmin4浏览0评论

I want to send visitors to my search.php after a search to display list of posts. If there is only one search result, user can directlyto the post in question(something like GOOGLE's I am Feeling Lucky Button)

Thank you all.

I want to send visitors to my search.php after a search to display list of posts. If there is only one search result, user can directlyto the post in question(something like GOOGLE's I am Feeling Lucky Button)

Thank you all.

Share Improve this question asked Oct 30, 2013 at 7:00 Marissa TweelMarissa Tweel 834 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 12

Add this snippet to your functions.php

function redirect_the_single_post() {
    if (is_search() && is_main_query()) {
        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_the_single_post' );

hope this will help you!!

发布评论

评论列表(0)

  1. 暂无评论