WordPress: Register Taxonomy Example (register_taxonomy)

If you create a new Post type in WordPress, it’s often useful to add a custom Taxonomy (similar to categories / tags on Posts). In this case, we’re adding an “error message” type (that contains lots of lists of error messages), and adding a “library” taxonomy, for which Javascript library the error comes from.

To do this, you first need to register the new type, in functions.php:

add_action( 'init', 'create_post_type' );
function create_post_type() {
  register_post_type( 'error_message',
    array(
      'labels' => array(
        'name' => __( 'Errors' ),
        'singular_name' => __( 'Error' )
      ),
      'public' => true,
      'has_archive' => true,
    )
  );
 
  ...
}

When you customize WordPress, it seems to be quite sensitive about you making labels for all the spots you might use the thing.

So, before we add the taxonomy, we have to write labels for everything:

$labels = array(
  'name'              => _x( 'Libraries', 'taxonomy general name' ),
  'singular_name'     => _x( 'Library', 'taxonomy singular name' ),
  'search_items'      => __( 'Search Libraries' ),
  'all_items'         => __( 'All Libraries' ),
  'parent_item'       => __( 'Parent Library' ),
  'parent_item_colon' => __( 'Parent Library:' ),
  'edit_item'         => __( 'Edit Library' ),
  'update_item'       => __( 'Update Library' ),
  'add_new_item'      => __( 'Add New Library' ),
  'new_item_name'     => __( 'New Library Name' ),
  'menu_name'         => __( 'Library' ),
);

Then, finally we can create the taxonomy (note the slug is important – this determines URLs in use):

$args = array(
  'hierarchical'      => false,
  'labels'            => $labels,
  'show_ui'           => true,
  'show_admin_column' => true,
  'query_var'         => true,
  'rewrite'           => array( 'slug' => 'library' ),
);
 
register_taxonomy( 'library_category', 'error_message', $args );