Veer.Y
Veer.Y

Reputation: 105

Query to get Attributes based on Product Category selected in WooCommerce?

I need to implement custom functionality like "Product filter by Attributes" widget works in woocommerce.

For example in Product category page: In Parent Category like Clothing, it loads all the attributes filter (pa_color , pa_size).

enter image description here

Now, when you check sub-category of that parent category i.e., Hoodies. It gets filtered and loads only related attributes (pa_color).

enter image description here

Please suggest the query to achieve this requirement.

Upvotes: 0

Views: 2138

Answers (1)

Veer.Y
Veer.Y

Reputation: 105

This is how I am getting the data as per my requirement :

        $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);

Upvotes: 3

Related Questions