调用woocommerce_product_query时需要重新加载页面两次

时间:2018-10-17 11:07:11

标签: php wordpress woocommerce hook-woocommerce

在我的functions.php中有这3个函数(对新手代码很抱歉)。

有一个提交按钮和一个下拉菜单。用户在选项列表中选择一个国家,然后按提交。然后运行custom_product_query_tax_query,并按Denmark名丹麦或欧罗巴对产品进行排序。它正在工作,但是,我需要按两次提交按钮,或者至少手动重新加载页面才能看到更改。

我是否需要在其他内容之前调用woocommerce_product_query,还是只是做错了所有事情?

//Before shop loop we inject the dropdown form with submit button.
//We also preselect the last option choosen, based on the country in session.
function report_button()
{
    // display button only on posts
    if ( !is_single() )
    {
    $retrive_data = WC()->session->get( 'Country' );
        $denmark = '';
        $europe = '';
        if($retrive_data === 'Denmark')
        {
            $denmark = 'selected';
        }
        else
        {
            $europe = 'selected';
        }
    $content .= '<form action="" method="POST">
                    <select name="select_name[]" id="">
                        <option value="Europe" '. $europe .'>Vis alle produkter</option>
                        <option value="Denmark" '. $denmark .'>Vis kun lovlige i Danmark</option>
                    </select>
                <input type="submit">
                </form>';
    echo $content;
    }
}
add_action( 'woocommerce_before_shop_loop', 'report_button', 10 );

//On submit, we set the selected country in a session variable.
add_action( 'template_redirect', 'wpse149613_form_process' );
function wpse149613_form_process()
{
    if(isset($_POST['select_name'])){ // select_name will be replaced with your input filed name
        $getInput = $_POST['select_name']; // select_name will be replaced with your input filed name
        foreach ($getInput as $option => $value) {
            $selectedOption = $value;
            WC()->session->set( 'Country' , $selectedOption );
        }
    }
}

//Custom woocommerce product query, show only products with Slug, Denmark.
function custom_product_query_tax_query( $q )
{
    if( is_admin() ) return $q;

    $retrive_data = WC()->session->get( 'Country' );

    if ( $retrive_data == 'Denmark' )
    {        
        $tax_query = (array) $q->get( 'tax_query' );

        $tax_query[] = array(
               'taxonomy' => 'product_tag',
               'field' => 'slug',
               'terms' => array( 'Denmark' ),
               'operator' => 'IN'
        );
        $q->set( 'tax_query', $tax_query );
    }
    else
    {
        return $q;
    }
}
add_filter( 'woocommerce_product_query', 'custom_product_query_tax_query', 10, 2 );

1 个答案:

答案 0 :(得分:0)

好的,我似乎在其他地方找到了答案。 template_redirect函数挂钩,需要重定向到某个地方。我将其添加到代码的底部,并且可以正常工作!

if ( !isHidden ) {
  seats.push( <withButton> )
}