Wordpress custom taxonomies

June 2, 2010 | Wordpress tutorials | No Comments »

Wordpress custom taxonomy is a very powerful and useful feature, you can classify posts in many different ways, for example: movies, music, photos, artists, actors or anything else.
So how to create custom taxonomy? Well let’s look at the example below.
This code will register custom taxonomy:

<?php

//this code must be placed in functions.php file.

add_action( 'init', 'create_my_taxonomies', 0 );

function create_my_taxonomies() {
register_taxonomy( 'company', 'post', array( 'hierarchical' => false, 'label' => 'Company', 'query_var' => true, 'rewrite' => true ) );
register_taxonomy( 'my_taxonomy', 'post', array( 'hierarchical' => false, 'label' => 'My Taxonomy', 'query_var' => true, 'rewrite' => true ) );
}

?>
  • my_taxonomy – custom taxonomy name
  • My taxonomy – custom taxonomy label
  • hierarchical – can be used as true/false

False – non hierarchical tag type taxonomy, true – hierarchical category type taxonomy.
For now you must use “false”, because hierarchical custom taxonomies will be supported just in wordpress 3.0.

After you have made changes in functions.php file you can go to wordpress admin panel to check if everything works.

Custom taxonomy panels


Getting custom taxonomy terms on your page

Tagcloud

It’s very easy to make a tagcloud from taxonomy terms, just set the taxonomy argument.
You can place this code whatever you want.

<?php wp_tag_cloud( array( 'taxonomy' => 'my_taxonomy', 'number' => 45 ) ); ?>

List taxonomy terms for each post

<?php echo get_the_term_list( $post->ID, 'my_taxonomy', 'My Taxonomy: ', ', ', '' ); ?>

Custom taxonomy template hierarchy

  • taxonomy.php – for all custom taxonomies
  • taxonomy-{taxonomy-name}.php – template for some taxonomy
  • taxonomy-{taxonomy-name}-{term}.php – template for taxonomy term

Leave a Reply