In WordPress, a taxonomy is a way to group and organize content, such as posts, pages, or custom post types.
Taxonomies are used to create relationships between content by grouping them based on shared characteristics or attributes.
WordPress comes with two built-in taxonomies:
- Categories
- Tags
So what is the difference between Categories and Tags?
If you want to create a custom taxonomy WordPress provides a function.
register_taxonomy();
`register_taxonomy()` is a function in WordPress that is used to register a new custom taxonomy, which is a way to group and organize content.
register_taxonomy($taxonomy, $object_type, $args);
- `$taxonomy` (string): The name of the taxonomy. This should be unique and lowercase with no spaces (e.g “category” and “post_tag”).
- `$object_type` (array|string): The name of the post type(s) to which the taxonomy should be applied. For example, if you want the taxonomy to apply to posts and pages, you would use `array(‘post’, ‘page’)`.
- `$args` (array): Optional arguments to customize the behavior oof the taxonomy. this can include options such as labels, capabilities, and hierarchical vs non-hierarchical.
Here’s an example of how you might use
register_taxonomy() to create a custom taxonomy for a fictional “Products” post type:
function my_custom_taxonomy() {
$labels = array(
'name' => __( 'Product Categories' ),
'singular_name' => __( 'Product Category' ),
'search_items' => __( 'Search Product Categories' ),
'all_items' => __( 'All Product Categories' ),
'parent_item' => __( 'Parent Product Category' ),
'edit_item' => __( 'Edit Product Category' ),
'update_item' => __( 'Update Product Category' ),
'add_new_item' => __( 'Add New Product Category' ),
'new_item_name' => __( 'New Product Category Name' ),
'menu_name' => __( 'Product Categories' )
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'show_admin_column' => true,
'query_var' => true
);
register_taxonomy( 'product_category', 'product', $args );
}
add_action( 'init', 'my_custom_taxonomy' );
This code creates a custom taxonomy called “Product Categories” for a post type called “Products”. The taxonomy is hierarchical (meaning it can have parent and child terms), has an admin column to display terms in the post list, and can be queried by URL parameters. The labels for the taxonomy are customized using the $labels array..