查询以根据WooCommerce中选择的产品类别获取属性?

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

例如在“产品类别”页面中: 在“父类别”(如“服装”)中,它将加载所有属性过滤器(pa_color,pa_size)。

查询以根据WooCommerce中选择的产品类别获取属性?

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

查询以根据WooCommerce中选择的产品类别获取属性?

请提出查询以达到此要求。

prince1594 回答:查询以根据WooCommerce中选择的产品类别获取属性?

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

        $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);
本文链接:https://www.f2er.com/3046810.html

大家都在问