woocommerce: add value to a product attribute

匿名 (未验证) 提交于 2019-12-03 01:11:01

问题:

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?

回答1:

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.



回答2:

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:

  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!



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!