Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
namespace WooCommerce_Helpers {
/**
* Looks for an existing WooCommerce attribute with the same label, or else
* creates a new attribute using the provided information.
*
* If a new attribute is successfully created, or an existing attribute is
* matched, the attribute object will be returned. Otherwise, bool false is
* returned.
*
* Note that when looking for existing attributes, the name is compared case
* insensitively ('license' matches 'License'). In the interests of avoiding
* confusion, it's also worth noting that the $label argument corresponds to
* the 'attribute_label' property in the returned attribute object, but to
* the 'name' argument in the context of a wc_create_attribute() call.
*
* @version WooCommerce 3.8.x
*
* @param string $label
* @param string $type
* @param string $orderby
* @param bool $public
*
* @return object|false
*/
function get_or_create_attribute( string $label, string $type = 'select', $orderby = 'menu_order', bool $public = true ) {
// Case insensitively match any existing attributes.
foreach ( wc_get_attribute_taxonomies() as $attribute ) {
if (
property_exists( $attribute, 'attribute_label' )
&& strtolower( $attribute->attribute_label ) === strtolower( $label )
) {
return $attribute;
}
}
// Otherwise, create a new attribute. Note that when we use wc_create_attribute(),
// the 'name' argument corresponds to 'label' as returned by wc_get_attribute().
$attribute_id = wc_create_attribute( [
'name' => $label,
'type' => $type,
'orderby' => $orderby,
'public' => $public,
] );
return is_wp_error( $attribute_id ) ? false : wc_get_attribute( $attribute_id );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.