Return to Snippet

Revision: 69317
at May 28, 2015 05:43 by adambundy


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

Initial URL
http://wpsnipp.com/index.php/functions-php/redirect-to-post-when-search-query-returns-single-result/

Initial Description
Courtesy Kevin Chard at WPSnipp.com. 

Adding this snippet to the functions.php of your wordpress theme will redirect your search to the post automatically when wordpress only returns a single search result.

Initial Title
WordPress - redirect to the post instead of archive page when search query returns single result

Initial Tags
php, wordpress

Initial Language
PHP