custom taxonomy - Check if any available product has specific attribute

admin2025-01-07  4

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.

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.

Share Improve this question asked Feb 18, 2020 at 21:39 pstidsenpstidsen 536 bronze badges 1
  • Have a look at this: github.com/woocommerce/woocommerce/wiki/… and this: wordpress.stackexchange.com/questions/272619/… – Andrea Somovigo Commented Feb 19, 2020 at 0:22
Add a comment  | 

1 Answer 1

Reset to default 1

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;
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736262033a787.html

最新回复(0)