【问题标题】:Query to get Attributes based on Product Category selected in WooCommerce?根据在 WooCommerce 中选择的产品类别查询以获取属性?
【发布时间】:2020-03-19 04:09:24
【问题描述】:

我需要在 woocommerce 中实现自定义功能,例如“按属性筛选产品”小部件。

例如在产品类别页面中: 在像 Clothing 这样的父类别中,它会加载所有属性过滤器(pa_color,pa_size)。

现在,当您检查该父类别的子类别时,即帽衫。它被过滤并仅加载相关属性(pa_color)。

请提出查询以实现此要求。

【问题讨论】:

    标签: wordpress woocommerce filter categories product


    【解决方案1】:

    这就是我根据我的要求获取数据的方式:

            $filter_raw = array(); 
            $attrs_raw  = wc_get_attribute_taxonomy_names(); // Getting data of attributes assign in backend.
            $cat_name = get_term($request['category'], 'product_cat', ARRAY_A ); //Category data by category ID.
            $args = array(
                'category'  => array($cat_name['slug'] )
            );
    
            foreach( wc_get_products($args) as $product ){
                foreach( $product->get_attributes() as $attr_name => $attr ){
                $filter_raw[] = $attr_name;
                if(is_array($attr->get_terms())){    
                    foreach( $attr->get_terms() as $term ){
                        $terms_raw[] = $term->name;
                    }
                }
                }
            }
            $filters = array_unique(array_intersect((array)$filter_raw,(array)$attrs_raw)); //Filtering the attributes used by products in particular category
            if(is_array($filters)){    
            foreach ( $filters as $filter ){
                $terms = get_terms( $filter );
                if ( ! empty( $terms ) ) {
    
                    $return['items'][ $filter ] = array(
                        'id'    => $filter,
                        'type'  => 'checkbox',
                        'label' => $this->decode_html( wc_attribute_label( $filter ) ),
                    );
                    foreach ( $terms as $term ) {
                        if(in_array($term->name,$terms_raw)){ //Filtering the terms from attribute used by the products in a category and showing required result.
                        $return['items'][ $filter ]['values'][] = array(
                            'label' => $this->decode_html( $term->name ),
                            'value' => $term->slug,
                        );
                        }
                    }
                }
            }
            }
            print_r($return);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-31
      • 2018-03-17
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多