Wednesday, April 10, 2013

Redirect to post if search results only returns one post

In Wordpress when a visitor search your website using WordPress built-in search engine function, the search results are displayed as a list. The following functionality can improve the search engine by automatically redirecting the visitor to the post if there is only one post is found by WordPress search engine.


You need to just paste the following code into the functions.php file:

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

No comments:

Post a Comment

I just got my #domain @BigRock. Get upto 25% off with my personalized coupon link Get upto 25% off