wp custom taxonomy code example

Example 1: custom post type with taxonomy

//hook into the init action and call create_book_taxonomies when it fires
add_action( 'init', 'create_topics_hierarchical_taxonomy', 0 );
 
//create a custom taxonomy name it topics for your posts
 
function create_topics_hierarchical_taxonomy() {
 
// Add new taxonomy, make it hierarchical like categories
//first do the translations part for GUI
 
  $labels = array(
    'name' => _x( 'Topics', 'taxonomy general name' ),
    'singular_name' => _x( 'Topic', 'taxonomy singular name' ),
    'search_items' =>  __( 'Search Topics' ),
    'all_items' => __( 'All Topics' ),
    'parent_item' => __( 'Parent Topic' ),
    'parent_item_colon' => __( 'Parent Topic:' ),
    'edit_item' => __( 'Edit Topic' ), 
    'update_item' => __( 'Update Topic' ),
    'add_new_item' => __( 'Add New Topic' ),
    'new_item_name' => __( 'New Topic Name' ),
    'menu_name' => __( 'Topics' ),
  );    
 
// Now register the taxonomy
 
  register_taxonomy('topics',array('post'), array(
    'hierarchical' => true,
    'labels' => $labels,
    'show_ui' => true,
    'show_admin_column' => true,
    'query_var' => true,
    'rewrite' => array( 'slug' => 'topic' ),
  ));
 
}

Example 2: custom taxonomy - wordpress

/*
* Plugin Name: Course Taxonomy
* Description: A short example showing how to add a taxonomy called Course.
* Version: 1.0
* Author: developer.wordpress.org
* Author URI: https://codex.wordpress.org/User:Aternus
*/
 
function wporg_register_taxonomy_course() {
     $labels = array(
         'name'              => _x( 'Courses', 'taxonomy general name' ),
         'singular_name'     => _x( 'Course', 'taxonomy singular name' ),
         'search_items'      => __( 'Search Courses' ),
         'all_items'         => __( 'All Courses' ),
         'parent_item'       => __( 'Parent Course' ),
         'parent_item_colon' => __( 'Parent Course:' ),
         'edit_item'         => __( 'Edit Course' ),
         'update_item'       => __( 'Update Course' ),
         'add_new_item'      => __( 'Add New Course' ),
         'new_item_name'     => __( 'New Course Name' ),
         'menu_name'         => __( 'Course' ),
     );
     $args   = array(
         'hierarchical'      => true, // make it hierarchical (like categories)
         'labels'            => $labels,
         'show_ui'           => true,
         'show_admin_column' => true,
         'query_var'         => true,
         'rewrite'           => [ 'slug' => 'course' ],
     );
     register_taxonomy( 'course', [ 'post' ], $args );
}
add_action( 'init', 'wporg_register_taxonomy_course' );

Tags:

Misc Example