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

I found a solution that works for now, with some reservations.

First, the field is available via meta_query, although previously I couldn’t find it because the object name is different than the database name. In the WC_Product class it is: [“attributes”]=>array(1)… However I found that the database field name is “product_attributes” and I can use “_product_attributes” as the key in a meta_query.

However, the next challenge is that the product_attributes database field contains serialized data, like this:

a:1:{s:14:"pa_myproductid";a:6:{s:4:"name";s:14:"pa_myProductID";s:5:"value";s:6:"123456";s:8:"position";i:0;s:10:"is_visible";i:1;s:12:"is_variation";i:0;s:11:"is_taxonomy";i:0;}}

So, this works…

$myProductIdToFind = array('a:1:{s:14:"pa_myproductid";a:6:{s:4:"name";s:14:"pa_myProductID";s:5:"value";s:6:"123456";s:8:"position";i:0;s:10:"is_visible";i:1;s:12:"is_variation";i:0;s:11:"is_taxonomy";i:0;}}');

$meta_query[] = array(
    array(
        'key'     => '_product_attributes',
        'value'   => $myProductIdToFind,
        'compare'     => 'IN',
        )
    );

Obviously, the value field is too complicated to use in production, so this isn’t a viable solution.

Next, I tried looping like this…

$myProductIdToFind = array('123456', '654321');

if (count($myProductIdToFind) > 1) {
    $meta_query[0] = array('relation' => 'OR');
}
foreach ($myProductIdToFind as $key => $metaValue) {
    $meta_query[0][] = array(
        'key'     => '_product_attributes',
        'value'   => $metaValue,
        'compare' => 'LIKE',
    );
} 

This works, although my reservation is regarding performance using ‘LIKE’ to compare. It’s fast enough for my sample of five products, but in production it might need to support 100 products or more. So I would prefer to narrow down the key and use ‘IN’ to compare against an array of values. But for now, it works!