Reputation: 31
Im trying to get a searchform to redirect instantly to the desired page if the search query is an exact match with a page title. I have found this piece of code which comes pretty close, but i fail to see why its not working like it should.
This is in my functions.php
// Redirect on exact match
function lab_title_match() {
if (is_search()) {
global $wp_query,$wpdb;
$s_str = $wp_query->query_vars['s'];
$m = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_title = %s",$s_str));
if (!empty($m)) {
wp_safe_redirect(get_permalink($m));
exit();
}
}
}
add_filter('pre_get_posts','lab_title_match');
This results in a redirect to domain.com/keyword/keyword/ instead of just domein.com/keyword/. I rewrote this multiple times while still getting the same result, so its probably me.
Thanks in advance :)
Upvotes: 2
Views: 767
Reputation: 31
I resolved it another way. Instead of an exact search i redirect as long as there is only 1 result.
// Redirect on 1 result
add_action('template_redirect', 'lab_redirect');
function lab_redirect() {
if (is_search()) {
global $wp_query;
if ($wp_query->post_count == 1) {
wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
}
}
}
Upvotes: 1