Question

I want to add list of color to a product attribute with following code:

function wcproduct_set_attributes($post_id, $_attributes) {
        $i = 0;
            foreach ($_attributes as $name => $value) {
                wp_set_object_terms($post_id, $value, $name);
                $product_attributes[$i] = array (
                    'name' => $name, // set attribute name
                    'value' => $value, // set attribute value
                    'is_visible' => 0,
                    'is_variation' => 1,
                    'is_taxonomy' => 1
                );
            }
            $i++;

        update_post_meta($post_id, '_product_attributes', $product_attributes);
    };

    wcproduct_set_attributes($_product_id_data, $my_product_attributes);

$product_attributes is an array of colors and $name is pa_color and $value is color name. this function works but it add last color to pa_color.

Was it helpful?

Solution

If we look at the official documentation, this is how wp_set_object_terms is used:

wp_set_object_terms( int $object_id, string|int|array $terms, string $taxonomy, bool $append = false )

Notice the final parameter that isn't being used in your code, it has a default value of false:

bool $append = false )

So everytime your loop runs, it wipes the slate clean and sets the terms rather than adding them. You need to pass the final parameter.

Also consider deliberatly calling this with a blank array before your loop so that terms can be unset. Alternatively, add them to an array and do a single call after the loop

Make sure in these situations to always read the official API docs at https://developer.wordpress.org

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top