0

How can you check if there are any products with a specific product attribute in the shop?

I could query (eg. with wc_get_products()) all products and check if they (or their variations) are in stock and then collect all the attribute values in an array and test the specific attribute against that array.

However, I think that sounds like a huge amount of database requests so I wondered if there is an easier path that I am missing.

0

Here is the code that solved the problem:

$woo_args = array(
    'status'        => 'publish',
    'limit'         => 1,
    'stock_status'  => 'instock',
    'brand'         => 99
);
$products = wc_get_products($woo_args);

if (count($products) == 0){
   //No product with the custom attribute id=99
}

add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2);
function my_handle_custom_query_var($query, $query_vars) {
    if (!empty($query_vars['brand'])){
        $query['tax_query'][] = array(
            'taxonomy' => 'pa_brand',
            'field'    => 'id',
            'terms'    => $query_vars['brand'],
            'operator' => 'IN',
        );
    }
    return $query;
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.