Filter on a custom product attribute in WooCommerce using meta_query or tax_query


I’m trying to filter on a “custom product attribute” using either a meta_query, a tax_query, or whatever method works. I can find the attribute using the WC_Product class, but haven’t figured out how to filter it. In the past I have successfully used both meta_query and tax_query on other fields, but anything I try with this custom attribute returns no results.

First, I manually entered a custom product attribute through the WooCommerce section in the WordPress Admin:

Products… Edit product… Attributes… Custom product attribute

Assume the post ID is 123, the custom product attribute’s name is “pa_myProductID” and the value is “123456”

The goal of this example is to only return products where pa_myProductID = “123456”

Here’s what I’ve tried without success:

add_action( 'woocommerce_product_query', 'show_products_by_myProductID' );
function show_products_by_myProductID( $q ) {
    $myProductIdToFind = array('123456');

First I tried a meta_query…

    $meta_query = $q->get( 'meta_query' );

    $meta_query[] = array(
        'key'     => 'pa_myproductid', // also tried 'pa_myProductID'
        'compare'     => '=',
        'value'   => $myProductIdToFind,

    $q->set( 'meta_query', $meta_query );

…but there are no results

Then I tried a tax_query…

    $tax_query = $q->get( 'tax_query' );

    $taxonomy = 'pa_myproductid'; // also tried 'pa_myProductID'
    $tax_query[] = array(
        'taxonomy'  => $taxonomy,
        'field'     => 'slug', // also tried 'name' and 'term_id' and 'term_taxonomy_id'
        'operator'  => 'IN',
        'terms'     => $myProductIdToFind,

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

…also with no results

I can find the attribute using the WC_Product class.

var_dump( wc_get_product('123') );

Here is some of the result:

object(WC_Product_Simple)#2617 (12) { 
["data":protected]=> array(50) { 
    ["attributes"]=> array(1) { 
        ["pa_myproductid"]=> object(WC_Product_Attribute)#2666 (1) { 
            ["data":protected]=> array(6) { 
                ["id"]=> int(0) 
                ["name"]=> string(11) "pa_myProductID" 
                ["options"]=> array(1) { 
                    [0]=> string(6) "123456" 
                ["position"]=> int(0) 
                ["visible"]=> bool(true) 
                ["variation"]=> bool(false) 
    ["default_attributes"]=> array(0) { } 
    ["menu_order"]=> int(5) 

I can display the attribute like this…

$productGot = wc_get_product('123');
 echo "Name: ";
 echo " -- Value: ";

output of above is…

Name: string(14) "pa_myProductID" -- Value: string(6) "123456"

Can someone help with the syntax or maybe another approach? Any assistance is greatly appreciated! Thanks!

, Tim 222 10 months 0 Answers 68 views 0

Leave an answer