最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Redirect Search to Form When No Product Results Are Found

programmeradmin2浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 2

pre_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' );
发布评论

评论列表(0)

  1. 暂无评论