The products in my clients website require certain attributes which I have added via Products -> Attributes in the WordPress administration. In this import script I’m coding I need to use the function update_post_meta($post_id, $meta_key, $meta_value)
to import the proper attributes and values.
Currently I have the function like so:
update_post_meta( $post_id, '_product_attributes', array());
However I’m not sure how to properly pass along the attributes and their values?
Right so it took me a while to figure it out myself but I finally managed to do this by writing the following function:
I hope this function will help other people if they need to import multiple attributes pro-grammatically in WooCommerce!
I tried Daniel’s answer, and it didn’t work for me. It might be that the WordPress/Woocommerce code has changed since, or perhaps I didn’t quite understand how to do it, but either way that code did nothing for me. After a lot of work using it as a base, however, I came up with this snippet of code and put it on my theme’s
functions.php
:With this, I can take what I set as “material” on my WooCommerce install as a custom attribute and add it to the formal meta as _material. This in turn allows me to use another snippet of code so the WooCommerce search function extends to meta fields, meaning I can search for a material in the WooCommerce search field and have all items with that material appear.
I hope this is useful to somebody.
@Daniels’s answer works, won’t decide on right or wrong, however if you want to add the values as a taxonomy term under attributes you have to adapt the code as below (set is_taxonomy = 1). Otherwise Woocommerce sees it as custom meta field(?). It still adds the value under attributes. This will only work for strings. For values that are arrays the code has to be adapted.
Additionally it uses the wp_set_object_terms that @Anand suggests as well. I was using that, because all the documentation I could find led to believe that had to be used. However if one only uses the wp_set_object_terms then I couldn’t see the attributes in the edit product screen. Using the information from both answers and reading on the subject resulted in the solution.
You will need to tweak the code for things such as product variations.
Then call the function:
Thank you for posting the code Daniel & Anand. It helped me a great deal.
Don’t know if this is the “correct” way to do this… But I needed a function to add ACF repeater fields with a date value as a attribute on post save, so this was the function I came up with:
Hope this helps someone.