How do I add value to a woocommerce attribute through code? I have created an attribute called 'Dispatch time' (taxonomy: pa_dispatch) and now I want to add value to a particular product's Dispatch attribute.
How to do this programmatically?
In this section,let me share how to update the product attributes programmatically in wordpress. Let's say we have a product attribute call "markup". We have to write like this in order to get the attribute correctly. $markup_value = get_post_meta($product->post_id, '_product_attributes',true)['markup']['value'];
Go to: Products > Add Product (or edit an existing one). Select the Attributes tab in the Product Data. There you can choose any of the attributes that you've created in the dropdown menu.
You cannot add value to an attribute. You need to make the product variable, create a variation, and assign it with the attribute. Now in this variation you can assign a value.
Read mode:
EDIT:
After more clarification on the question, here is an updated solution.
Add the below function to your functions.php. Call it on the appropriate hook and pass the product ID as well as the attribute values.
function se19519561_set_attributes($post_id, $attributes) {
//Type attribute
$product_attributes['type'] = array(
//Make sure the 'name' is same as you have the attribute
'name' => htmlspecialchars(stripslashes('Dispatch Time')),
'value' => $attributes,
'position' => 1,
'is_visible' => 1,
'is_variation' => 1,
'is_taxonomy' => 0
);
//Add as post meta
update_post_meta($post_id, '_product_attributes', $product_attributes);
}
Hope this helps!
I found the answer, you need to use wp_set_object_terms to set the terms of object of a taxonomy,
wp_set_object_terms( $object_id, $terms, $taxonomy, $append);
Where, $append can be true
or false
, if true, the tag will be appended to existing tag, if false, the tag is replaced.
In my example,
wp_set_object_terms( $object_id, '2 Business Days', 'pa_dispatch' , false);
Here, the pa_dispatch
is the woo-commerce taxonomy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With