can you please let me know how I can add Custom Product Attribute and Variable in WooCommerce Programatically? I know this easy to be done in Woocommerce GUI but I need to do this through functions.php
I have a Attribute Called “Class” and Some Variables as [A,B,C,D] now I would like to add them to the Cart and Shop page, I alraedy tried this function but it didn’t add any thing to the page:
function woocommerce_variable_add_to_cart() {
//Type attribute
$product_attributes['type'] = array(
//Make sure the 'name' is same as you have the attribute
'name' => htmlspecialchars(stripslashes('Class')),
'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);
}
Thanks
I just noticed that your function above refers a “$attributes” which doesn’t look like it’s defined in that function. Hopefully your working copy of that function fixed that otherwise value => NULL which probably is why your update failed.
On the other hand I think your $product_attributes is badly defined (I’m not 100% sure, though).
I created a custom attribute called “my_attr_name” with the value “my_custom_value” and checked the MySQL database to see how it is stored. It is stored inside table “wp_postmeta” with meta_key=_product_attributes and the “meta_value” serialized. So I copied that serialized value and tried to unserialize it just to see how it should be defined in the first place. It looks like yours except that your attribute key (ie. ‘type’) and the value for the first key of the subarray should match.
This is my example:
As you see the array’s key john-doe ~ first key of the subarray (which is also John Doe). In your case:
It worth mentioning that if your ‘name’ => ‘John Doe’ then the master key should be something like ‘john-doe’ (lower-case and minus as space replacement). I don’t know if this is a must but at least this is the way WP 4.2.2 works.
As for the other keys: