How to check if product has a specific product attribute in Woocommerce
Asked Answered
E

1

6

I would like to identify if a product has an attribute or not. For example:

if (product has attribute 'pa_color')
{
    //do something
}

How can I accomplish this?

Edina answered 7/4, 2018 at 21:55 Comment(1)
@LoicTheAztec Hey, sorry I forgot to mark it as the correct answer. Your answer worked for me thank you.Edina
I
19

You simply can use the WC_Product method get_attribute() this way:

// (If needed) Get an instance of the WC_Product Object from the product ID
$product = wc_get_product( $product_id );

// Get the product attribute value(s)
$color = $product->get_attribute('pa_color');

// if product has attribute 'pa_color' value(s)
if( ! empty( $color ) ){
    // do something
} else {
    // No product attribute is set for this product
}
Idiotic answered 7/4, 2018 at 23:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.