admin管理员组文章数量:1333705
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' );
本文标签: wp queryRedirect Search to Form When No Product Results Are Found
版权声明:本文标题:wp query - Redirect Search to Form When No Product Results Are Found 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742338878a2456189.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论