Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

woocommerce: add value to a product attribute

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?

enter image description here

like image 733
Nagendra Rao Avatar asked Oct 22 '13 13:10

Nagendra Rao


People also ask

How do I change product attribute value in WooCommerce?

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'];

How do I edit attributes in WooCommerce?

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.


2 Answers

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.

Attributes Configuration

Variations Configuration

Read mode:

  1. http://docs.woothemes.com/document/product-variations/
  2. http://www.youtube.com/watch?v=7PX8MWBOAeo

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!

like image 61
Sameer Joshi Avatar answered Oct 24 '22 22:10

Sameer Joshi


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.

like image 36
Nagendra Rao Avatar answered Oct 24 '22 20:10

Nagendra Rao