Create a custom taxonomy

Creating a custom taxonomy is pretty straight forward using the built in register_taxonomy function:

register_taxonomy('taxonomy_name', 'post_type_name',
   array(
      'hierarchical' => TRUE | FALSE,
      'label' => 'Taxonomy Name',
      'query_var' => TRUE,
      'rewrite' => array(
         'slug' => 'plural_taxonomy_name/[tag|category]',
         'with_front' => FALSE,
         'hierarchical' => FALSE,
      ),
   )
);

It’s important to understand that WordPress has no real differentiation between categories and tags. The only difference is purely from a WordPress Admin perspective, categories are shown as check-boxes whereas tags are displayed as free-form text fields. This difference is set by the hierarchical option in the data structure passed to register_taxonomy. Use TRUE for categories (check-boxes) and FALSE for tags (text fields).

Another important aspect of creating the taxonomy is the slug option passed to the rewrite structure. This option allows you to specify the URL path on which the template is displayed. Say e.g. that you have a custom post type named ingredient and the type of taxonomy you’re creating is a tag, then you could use a path such as ingredients/tagged as the following example illustrates:

register_taxonomy('ingredient_tags', 'ingredient',
   array(
      'hierarchical' => FALSE,
      'label' => 'Tags',
      'query_var' => TRUE,
      'rewrite' => array(
         'slug' => 'ingredients/tagged',
         'with_front' => FALSE,
         'hierarchical' => FALSE,
      ),
   )
);

In the above example we’re creating a new tag based taxonomy. Our taxonomy name is ingredient_tags and is used to identify our taxonomy when calling specific taxonomy related WordPress functions. As you can see, the slug is set to ingredients/tagged which is the prefix for this taxonomy’s URL. If we where to create a tag called taxonomy then the URL to that tag would be ingredients/tagged/taxonomy and it would trigger the template taxonomy-ingredient_tags.php. The post loop on that template will then only have posts of type ingredient tagged with the term taxonomy.

Bon App├ętit!

Tagged with: