Redirect to the one post found in search results

When you search on a WordPress website, you always get the results page in return. Even when the result is just one post or page.

With the code below you can skip the results page when the search result is just one post or page. You will be sent directly to that post or page. This saves your visitors one mouse click!

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 ) );

Add this code to the functions.php of your theme and test the modified search.

Always backup your functions.php before you start changing it!

Ronald Heijnes
Ronald Heijnes

Since 2008 I keep myself busy with the functionality, management, maintenance and performance of self hosted WordPress. I like to share this knowledge. All in my spare time!

Articles: 44

Leave a Reply

Your email address will not be published. Required fields are marked *