Site has an internal product search. If a query has no results, I want to redirect to a contact form, and pass the query through into the form into the product name field. The problem I'm having is with the conditional statement. I've written some code to determine if the query is a search, and if it has results. When I write an If statement with && it always evaluates to false. If I nest them as below, it works, but this cant be ideal. I'm sure the answer is simple, but I am not very familiar with php syntax. Thanks.
function no_products_found_redirect($query) {
$search = $query->query['s'];
if ( $query->is_search() ){
if ( have_posts() ) {
echo 'dont do anything';
}
else{
wp_redirect ( home_url('/request-quote/?product_name=')) . $search;
exit;
}
}
}
add_action( 'pre_get_posts', 'no_products_found_redirect' );
Site has an internal product search. If a query has no results, I want to redirect to a contact form, and pass the query through into the form into the product name field. The problem I'm having is with the conditional statement. I've written some code to determine if the query is a search, and if it has results. When I write an If statement with && it always evaluates to false. If I nest them as below, it works, but this cant be ideal. I'm sure the answer is simple, but I am not very familiar with php syntax. Thanks.
function no_products_found_redirect($query) {
$search = $query->query['s'];
if ( $query->is_search() ){
if ( have_posts() ) {
echo 'dont do anything';
}
else{
wp_redirect ( home_url('/request-quote/?product_name=')) . $search;
exit;
}
}
}
add_action( 'pre_get_posts', 'no_products_found_redirect' );
Share
Improve this question
asked Jun 17, 2020 at 21:25
imatecimatec
1
1 Answer
Reset to default 2pre_get_posts
is fired before the query is run and is used to customize the query before its is run.
See here for a list of hooks, they are listed in order of execution. https://codex.wordpress/Plugin_API/Action_Reference
I would suggest using a hook that fires after the query is run for example, template_redirect
is fired immediately after the query is run.
function no_products_found_redirect() {
global $wp_query;
if ( $wp_query->is_search && !have_posts() ){
wp_redirect ( home_url('/request-quote/?product_name=' . get_search_query() ) );
exit;
}
}
add_action( 'template_redirect', 'no_products_found_redirect' );