Cray
Cray

Reputation: 5483

WooCommerce: Check if product has a specific attribute

I want to check if a product has a specific attribute. But it's possible that the attribute is only on of many.

For example, the product has the attribute language pa_sprog and it has more than one languages. But I want to check if it has the language "english" in it.

I found this great code (https://stackoverflow.com/a/60295332/1788961):

// for debug purposes, place in comment tags or delete this code
    $product_attributes = $product->get_attributes();
    echo '<pre>', print_r($product_attributes, 1), '</pre>';

    // Get the product attribute value
    $sprog = $product->get_attribute('pa_sprog');

    // if product has attribute 'sprog' value(s)
    if( $sprog == "english" ) {
        echo '<div class="">yes!</div>';
    } else {
        echo '<div class="">no!</div>';
    }

But the code only works if the language "english" is the only value for that that attribute. If there are more than one, the code doesn't work anymore.

I tried to change the if-statement to check if the language is in the attribute array:

if( in_array( "english", $sprog) ) {

But it doesn't work.

Is there any other way?

Upvotes: 2

Views: 1082

Answers (1)

7uc1f3r
7uc1f3r

Reputation: 29614

It is not an array but a string, so you can use a strpos

global $product;

// for debug purposes, place in comment tags or delete this code
$product_attributes = $product->get_attributes();
echo '<pre>', print_r($product_attributes, 1), '</pre>';

// Get the product attribute value
$sprog = $product->get_attribute('pa_sprog');

// Gettype - Returns the type of the PHP variable var.
echo gettype($sprog) . '<br>';

// Result
echo $sprog . '<br>';

// If product has attribute 'sprog' value(s)
if( strpos($sprog, 'english') !== false ) {
    echo '<div class="">yes!</div>';
} else {
    echo '<div class="">no!</div>';
}

Related: WooCommerce: check if product has attribute

Upvotes: 2

Related Questions