You probably shouldn’t use this if you have really generic page/post titles, but it can be a really handy feature.
Basically, if a user searches for something that happens to be an exact match to a page or post you have, it’ll redirect the user to the page, rather than displaying search results.
add_action('template_redirect', 'seach_query_is_title'); function seach_query_is_title() { if (is_search()) { global $wp_query; if ( get_page_by_title( get_search_query(), 'OBJECT', 'post' ) ) { wp_redirect( get_permalink( get_page_by_title (get_search_query() )->ID ) ); } elseif ( get_page_by_title( get_search_query(), 'OBJECT', 'page' ) ) { wp_redirect( get_permalink( get_page_by_title( get_search_query() )->ID ) ); } } }
THanks for code. It is what I have been looking for. After I add the code to functions.php, is there anything else I need to do to make it work within the WordPress search?
After I placed it in my theme functions it did work. I did notice that it wasn’t necessarily an exact title match. It redirected to the first post that had the search term in the title. Is there a way to make the search a true exact make? For example my post are Scripture Verses. And so “John 1:1” is also going to be in “John 1:19” and so what is happening for me is that it is redirecting to “John 1:19” instead. Thanks for your time!