I am using WordPress 3.3.1 and new to this system. I want to redirect the search query to the post if query exactly matches post title of some post.
I also want it to run before any search query function and hooks or filter. I have made some changes in query.php in include folder
$search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}'))";
and wrote some plugin function like this:
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 ) );
}
}
}
I have also some function that need to run just after this search query and has “get_header” hooks. So far the search query match and redirect is not matching and returning as aspected. It most of the time slips out and don’t redirect perfectly. I want search and redirect to be very perfect.
Any help will be highly appreciated and thankful. Thank you.
First, don’t hack core files (unless you intend to submit a patch 🙂 ).
Second, what you are doing isn’t really checking to see if the title exactly matches the search string. What you are doing it checking to see if there is only one result. That doesn’t mean the title matches. Undo the core hack, then do this:
That is case sensitive. If you don’t want that use strtolower by making this change to line 6:
Also, this query runs after the WordPress search, which does not match what the OP requested. However, it is necessary to run a query so it makes sense to use the default query.
@Rarst notes below in the comments that this is not a completely reliable solution. I believe that to be true though I don’t know how much it would matter in practice. Here, however, is an option that should be reliable but adds a query to the search page.
As above, this is case sensitive.