How to add custom taxonomies in WordPress without plugins

In the same vein of our previous post about creating a Custom Post Type without plugins, here we’ll see how to create custom taxonomies.
In this example we create two taxonomies (director and year) to associate to an hypothetical custom post type called movie. You only need to paste the below code in your functions.php and modify what you need (check the comments).

/*
 * Add Custom Taxonomies
 */
function netgloo_custom_taxonomies() {

  $taxonomies = array(

    // Director
    array(
      'name'   => 'director', // here the name of the taxonomy
      'single' => 'Director', // here the single taxonomy name to show in the backend
      'plural' => 'Directors', // here the plural taxonomy name to show in the backend
      'cpt'    => 'movie' ), // which Custom Post Type to associate the taxonomy

    // Year
    array(
      'name'   => 'year',
      'single' => 'Year',
      'plural' => 'Years',
      'cpt'    => 'movie' )
  );

  foreach ($taxonomies as $taxonomy) {

    $name = $taxonomy['name'];
    $single = $taxonomy['single'];
    $plural = $taxonomy['plural'];
    $cpt = $taxonomy['cpt'];

    $labels = array(
      'name'              => _x( $plural, 'taxonomy general name' ),
      'singular_name'     => _x( $single, 'taxonomy singular name' ),
      'search_items'      => __( 'Cerca '. $plural ),
      'all_items'         => __( 'Tutte le '. $plural ),
      'parent_item'       => __( 'Parent '. $single ),
      'parent_item_colon' => __( 'Parent '. $single.':' ),
      'edit_item'         => __( 'Modifica '. $single ),
      'update_item'       => __( 'Aggiorna '. $single ),
      'add_new_item'      => __( 'Aggiungi '. $single ),
      'new_item_name'     => __( 'Nuova '. $single ),
      'menu_name'         => __(  $plural )
    );

    $args = array(
      'labels'            => $labels,
      'hierarchical' 	  => true,	// false: as Tags, true: as Category
      'show_ui'           => true,
      'show_admin_column' => true
    );

    register_taxonomy( $name, $cpt, $args );

  } //foreach
}
add_action( 'init', 'netgloo_custom_taxonomies', 0 );

Categories

Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow

Comments

Developed and designed by Netgloo
© 2017 Netgloo