Wordpress Woocommerce - 按带有条件的属性或按查询参数过滤

问题描述 投票:0回答:1

每个车轮可以有两种不同的螺栓图案(属性)

bolt-pattern, bolt-pattern-2

当我按特定汽车过滤时,我使用查询参数和过滤器,如下所示

https://wheeluniverse.com/YMM/wheels/?**filter_bolt-pattern=6X139-7**&query_type_finish=or&orderby=推荐

然后,这将打开按该螺栓模式过滤的页面,最终用户可以按属性进一步过滤:品牌、颜色......

问题:如何为螺栓模式设置条件“OR”,这意味着

filter_bolt-pattern=6X139-7 filter_bolt-pattern-2=6X139-7

我尝试使用通用查询参数,但似乎并不那么容易。

https://wheeluniverse.com/YMM/wheels/?orderby=recommended&filter_bolt-pattern=6x139-7&filter_bolt-pattern-2=6x139-7&query_type_bolt-pattern-2=or
wordpress woocommerce
1个回答
0
投票

安装了 Wordpress 和 WooCommerce,您可以通过以下方式实现:

  1. 检查查询参数并查看是否涉及这两个属性。这意味着在查询参数中你应该有
    filter_bolt-pattern=6x139-7&filter_bolt-pattern-2=6x139-7
  2. 使用它,您可以有一个 if 语句来检查它们是否都存在,以便修改 woocommerce 查询。

您要连接的钩子:

add_action('woocommerce_product_query', 'filter_products_by_bolt_pattern_or');

这是函数:

add_action('woocommerce_product_query', 'filter_products_by_bolt_pattern_or');

function filter_products_by_bolt_pattern_or( $q ) {
    if (isset($_GET['filter_bolt-pattern']) && isset($_GET['filter_bolt-pattern-2'])) {
        $tax_query = array('relation' => 'OR');

        $tax_query[] = array(
            'taxonomy' => 'pa_bolt-pattern',
            'field'    => 'name',
            'terms'    => $_GET['filter_bolt-pattern'],
        );

        $tax_query[] = array(
            'taxonomy' => 'pa_bolt-pattern-2',
            'field'    => 'name',
            'terms'    => $_GET['filter_bolt-pattern-2'],
        );

        $q->set('tax_query', $tax_query);
    }
}

还要记住,从安全角度考虑,这样使用 $_GET 的值并不是一个好的方法。你应该清理并转义这些值。 您可以阅读有关这些数据安全性的文档:https://developer.wordpress.org/apis/security/escaping/

© www.soinside.com 2019 - 2024. All rights reserved.