WordPress
wordpress php taxonomy
Register Custom Taxonomy
WordPress function to register a custom taxonomy with hierarchical support.
function register_custom_taxonomy() {
$labels = array(
'name' => _x('Categories', 'taxonomy general name', 'textdomain'),
'singular_name' => _x('Category', 'taxonomy singular name', 'textdomain'),
'search_items' => __('Search Categories', 'textdomain'),
'all_items' => __('All Categories', 'textdomain'),
'parent_item' => __('Parent Category', 'textdomain'),
'parent_item_colon' => __('Parent Category:', 'textdomain'),
'edit_item' => __('Edit Category', 'textdomain'),
'update_item' => __('Update Category', 'textdomain'),
'add_new_item' => __('Add New Category', 'textdomain'),
'new_item_name' => __('New Category Name', 'textdomain'),
'menu_name' => __('Categories', 'textdomain'),
);
$args = array(
'hierarchical' => true, // Like categories
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array('slug' => 'product-category'),
'show_in_rest' => true, // Enable in REST API
);
register_taxonomy('product_category', array('product'), $args);
}
add_action('init', 'register_custom_taxonomy');
Usage
// Get terms
$terms = get_terms(array(
'taxonomy' => 'product_category',
'hide_empty' => false,
));
// Get post terms
$post_terms = wp_get_post_terms($post_id, 'product_category');