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.
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.
Share Improve this question asked Jun 1, 2020 at 8:35 Web DesignWeb Design 32 bronze badges 5 |1 Answer
Reset to default 0If 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
pa_color
, but you've not mentionedpa_color
before so I don't know what you're referring to. There are a few other things that don't make sense, such as wheremy_product_attributes
comes from, or how you're testing this. Keep in mind that WooCommerce is a 3rd party plugin, and 3rd party plugin dev support is off topic here and not in this stacks scope – Tom J Nowell ♦ Commented Jun 1, 2020 at 8:52