Redirect to post if search results return one post

Redirect to post if search results return one post

Online by JSC0d3
July 22, 2016 | | 125 recognitions

When you search for something on a WordPress website, a search results page is displayed with all relevant posts, posts, and other post types. The problem with this setup is that WordPress will still display a results page if there is only one blog post result.

This code snippet addresses this issue. If only one blog post is found for a search, the visitor will be taken directly to the blog post in question.

add_action('template_redirect', 'custom_redirect_single_post');
function custom_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;
        }
    }
}

 

JSC0d3's Logo
About JSC0d3

JSC0d3 is an entrepreneur, online marketer, and an employee of an IT company. When not building websites, creating content, or helping customers improve their online business, spend time with their wife and two beautiful children. Although he still feels new in WordPress, he enjoys sharing what he has learned with all of you! If you want to get in touch with him, you can do this through this website.

On the same idea

Posted by | April 1, 2019

Images are vital components of every website Before you start questioning the importance of images, just try to imagine your favorite blog or website...

Posted by | March 5, 2019

I’ve been loosely following the noise and #wpdrama surrounding Gutenberg for as long as it has been around and honestly for the most part I’ve...

Posted by | February 24, 2019

To ensure that your site ranks highly in Search Engine Result Pages (SERPs), you’ll need to make it easy for search engine ‘bots’ to explore...

Previous PostBackNext Post

Leave here an impression