Skip to content

Instantly share code, notes, and snippets.

@forsvunnet
Created September 4, 2019 11:54
Show Gist options
  • Save forsvunnet/741ba2d2908be7dc2d1a43a8846c2b74 to your computer and use it in GitHub Desktop.
Save forsvunnet/741ba2d2908be7dc2d1a43a8846c2b74 to your computer and use it in GitHub Desktop.
Create a WooCommerce product attribute programatically
<?php
// return;
add_action('init', function() {
$attribute_name = 'New a';
$attribute_id = 'new_a';//wc_attribute_taxonomy_id_by_name($attribute_name);
$attribute_slug = wc_attribute_taxonomy_name($attribute_id);//wc_attribute_taxonomy_id_by_name($attribute_name);
/*
* @type int $id Unique identifier, used to update an attribute.
* @type string $name Attribute name. Always required.
* @type string $slug Attribute alphanumeric identifier.
* @type string $type Type of attribute.
* Core by default accepts: 'select' and 'text'.
* Default to 'select'.
* @type string $order_by Sort order.
* Accepts: 'menu_order', 'name', 'name_num' and 'id'.
* Default to 'menu_order'.
* @type bool $has_archives Enable or disable attribute archives. False by default.
*/
if (! taxonomy_exists($attribute_slug)) {
$taxonomy_id = wc_create_attribute( [
'id' => $attribute_id,
'name' => $attribute_name,
'slug' => $attribute_slug,
] );
} else {
$taxonomy_id = wc_attribute_taxonomy_id_by_name($attribute_id);
}
$attribute = wc_get_attribute($taxonomy_id);
if (! $attribute || is_wp_error($attribute)) {
return;
}
$pa = new \WC_Product_Attribute();
$pa->set_id($taxonomy_id);
$pa->set_name($attribute_slug);
$pa->set_visible(false);
$pa->set_options(['Test 4']);
$product = wc_get_product(8814);
$product->set_attributes( [ $pa ] );
$product->save();
// die;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment