Last active
April 28, 2024 06:05
-
-
Save cyberdev/6386c1d2c05e71949dcb5951e5cdfb31 to your computer and use it in GitHub Desktop.
Get Taxonomy or Create when not exists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public function taxonomy_create($label) | |
{ | |
delete_transient('wc_attribute_taxonomies'); | |
\WC_Cache_Helper::incr_cache_prefix('woocommerce-attributes'); | |
// These are exported as labels, so convert the label to a name if possible first. | |
$attributeLabels = wp_list_pluck(wc_get_attribute_taxonomies(), 'attribute_label', 'attribute_name'); | |
//will produce | |
//$attributeLabels = ['<att_name>' => '<att_label>'] | |
$attributeWCName = array_search($label, $attributeLabels, true); | |
if (!$attributeWCName) { | |
$attributeWCName = wc_sanitize_taxonomy_name($label); | |
$attributeWCName = mb_substr($attributeWCName, 0, 27); | |
} | |
//$attributeSlug = 'pa_' . $attributeWCName; | |
$attributeId = wc_attribute_taxonomy_id_by_name($attributeWCName); | |
$taxonomyName = wc_attribute_taxonomy_name($attributeWCName); | |
if (!$attributeId) { | |
unregister_taxonomy($taxonomyName); | |
$attributeId = wc_create_attribute([ | |
'name' => $label, | |
'slug' => $attributeWCName, | |
'type' => 'select', | |
'order_by' => 'menu_order', | |
'has_archives' => 0, | |
]); | |
register_taxonomy($taxonomyName, apply_filters('woocommerce_taxonomy_objects_' . $taxonomyName, [ | |
'product', | |
]), apply_filters('woocommerce_taxonomy_args_' . $taxonomyName, [ | |
'labels' => [ | |
'name' => $label, | |
], | |
'hierarchical' => false, | |
'show_ui' => true, | |
'query_var' => true, | |
'rewrite' => false, | |
])); | |
} | |
return $taxonomyName; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment