Search code examples
phpwordpresswoocommerceproductcustom-taxonomy

Get specific product attribute values for a specific product category in Woocommerce


I have already managed to get all the color attributes with this code:

$color_terms = get_terms(
        array(
        'taxonmy'=>'pa_color'
    ));

This works fine for Shop page and returns all the colors but how can I limit it to a certain category? Lets say in a category named "Shirts" I have only 2 colors and I want to only show those 2 colors.


Solution

  • try the following custom function that use a unique light SQL query:

    function get_attribute_terms_in_product_cat( $category_term_name, $attribute_taxonomy ){
        global $wpdb;
    
        $terms = $wpdb->get_results( "SELECT DISTINCT t.*
            FROM {$wpdb->prefix}terms as t
            JOIN {$wpdb->prefix}term_taxonomy as tt ON tt.term_id = t.term_id
            JOIN {$wpdb->prefix}term_relationships as tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
            WHERE tt.taxonomy LIKE '$attribute_taxonomy'
            AND tr.object_id IN ( SELECT DISTINCT tr2.object_id
                FROM {$wpdb->prefix}term_relationships as tr2
                JOIN {$wpdb->prefix}term_taxonomy as tt2 ON tt2.term_taxonomy_id = tr2.term_taxonomy_id
                JOIN {$wpdb->prefix}terms as t2 ON tt2.term_id = t2.term_id
                WHERE tt2.taxonomy LIKE 'product_cat' AND t2.name = '$category_term_name'
            )" );
    
        return $terms;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.


    USAGE:

    // Get the "pa_color" attribute terms for product category "Shirts"
    $terms = get_attribute_terms_in_product_cat( "Shirts", "pa_color" );
    

    Here "Shirts" is a product category term name and "pa_color" the product attribute taxonomy…

    You will get an array of product attribute values (term object) containing:

    • the term ID (key term_id)
    • the term name (key name)
    • the term slug (key slug)

    You can use a foreach loop to access each term object:

    // Get the "pa_color" attribute terms for product category "Shirts"
    $terms = get_attribute_terms_in_product_cat( "Shirts", "pa_color" );
    
    // Loop through each term
    foreach( $terms as $term ){
        $term_id   = $term->term_id;
        $term_name = $term->name;
        $term_slug = $term->slug;
    }