I'm creating a Wordpress page that uses the native search. I have the following PHP code in my WPCode plugin which redirects based on 2 conditions.
- If search parameter equals a post title it will redirect to that post.
- If no post titles exist with the search parameter it will redirect to my custom no results found page.
Code:
//redirects search result to exact post page
function redir_rigid_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','redir_rigid_title_match');
//redirects zero search result to add review page
add_action('template_redirect', 'redirect_single_post');
function redirect_single_post() {
if (is_search()) {
global $wp_query;
if ($wp_query->post_count == 0) {
wp_redirect( 'https://example.com/no-search-results/' );
exit;
}
}
}
Works flawlessly but I would like to include the search input in the URL redirect for condition 2 so that the https://example.com/no-search-results/ becomes https://example.com/no-search-results/?s=[search input] when I've laded at the redirect page. So if someone searched "green cars" the url would land as https://example.com/no-search-results/?s=green+cars
I need the value of the search input for a function that is on my no search results page. Thus it needs to carry over.