Adding Attribute Programmatically in Product (Woocommerce)

Post teaching how to add an attribute programmatically in Woocommerce and how to relate it and a given value to a product (by ID)

Woocommerce is a plugin that adds ecommerce functionality to WordPress

Add the following function to the file functions.php of the theme being used

function create_product_attribute ($ label_name) {global $ wpdb; $ slug = sanitize_title ($ label_name); if (strlen ($ slug)> = 28) {return new WP_Error ('invalid_product_attribute_slug_too_long', sprintf (__ ('Name "% s" is too long (28 characters max) Shorten it, please.', 'woocommerce') , $ slug), array ('status' => 400)); } elseif (wc_check_if_attribute_name_is_reserved ($ slug)) {return new WP_Error ('invalid_product_attribute_slug_reserved_name', sprintf (__ ('Name "% s is not allowed because it is reserved term. $ slug), array ('status' => 400)); } elseif (taxonomy_exists (wc_attribute_taxonomy_name ($ label_name))) {return new WP_Error ('invalid_product_attribute_slug_already_exists', sprintf ($ _name_name,% s "is already in use. ), array ('status' => 400)); } $ data = array ('attribute_label' => $ label_name, 'attribute_name' => $ slug, 'attribute_type' => 'select', 'attribute_orderby' => 'name', 'attribute_public' => 0, // Enable archives ==> true (or 1)); $ results = $ wpdb-> insert ("{$ wpdb-> prefix} woocommerce_attribute_taxonomies", $ data); if (is_wp_error ($ results)) {return new WP_Error ('cannot_create_attribute', $ results-> get_error_message (), array ('status' => 400)); } $ id = $ wpdb-> insert_id; do_action ('woocommerce_attribute_added', $ id, $ data); wp_schedule_single_event (time (), 'woocommerce_flush_rewrite_rules'); delete_transient ('wc_attribute_taxonomies'); }

To add the attribute simply carry out the function call

create_product_attribute ('2 TEST');

Remembering that the file function.php is loaded / executed on every page request made in WordPress.

Relating Attribute to Product

Following you can relate the newly created attribute to the product using:

$ term_taxonomy_ids = wp_set_object_terms (get_the_ID (), 'ATTRIBUTE_VALUE', 'pa_ATTRIBUTE', true); $ thedata = Array ('pa_ATTRIBUTE' => Array ('name' => 'pa_ATTRIBUTE', 'value' => 'ATTRIBUTE_VALUE', 'is_visible' => '1', 'is_variation' => '1', 'is_taxonomy '=>' 1 ')); update_post_meta (get_the_ID (), '_ product_attributes', $ thedata);

Note:

  • Replace function "get_the_ID ()" with product ID.
  • pa_ATTRIBUTE by adding product code (always with "pa_" in the front)
  • ATTRIBUTE_VALUE by the desired value.

Rate This Article!

Click on the stars to give a note of 1 to 5.

1 star2 stars3 stars4 stars5 stars (No Ratings Yet)
Loading ...

Doubts? Make a comment below or send us a message by clicking here.

Your email address will not be published. Required fields are marked with *