Open (Re)source

How to register ‘new’ taxonomies to WordPress posts

By

Sometimes, you want more than just categories and tags on native WordPress Posts. Below is code you can add to your custom plugin to add a new taxonomy to native posts. The highlighted ‘post’ is the part of the code that connects this taxonomy to native posts. It’s the same way you’d connect a custom post type to a taxonomy. 

Below I’ve added the new taxonomy ‘Topics’ to the native WordPress posts.

The native taxonomies to the native WordPress post type "posts": "categories" and "tags"
The native taxonomies to the native WordPress post type “posts”: “categories” and “tags”
The custom taxonomy "topics" added to the native WordPress post type "posts."
The custom taxonomy “topics” added to the native WordPress post type “posts.”

The code below is how I added the new taxonomy to posts.

Register a new Taxonomy to native posts

// Creating a new taxonomy for posts - Topic
function create_topic_taxonomy() {
  $labels = array(
    'name' => _x( 'Topic', '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' ),
  );  

// register the taxonomy
  register_taxonomy('topic',array('post'), array(
    'hierarchical' => true,
    'labels' => $labels,
    'show_ui' => true,
    'show_in_rest' => true,
    'show_admin_column' => true,
    'query_var' => true,
    'rewrite' => array( 'slug' => 'topic', 'with_front' => FALSE ),
  ));
}
//hook into the init action and call create_book_taxonomies when it fires
add_action( 'init', 'create_topic_taxonomy', 0 );

In the code above, make sure in the register_taxonomy function that the array has ‘post’ (highlighted in yellow), this will target the native WordPress posts and attach this taxonomy to it. 

Leave a Reply

Your email address will not be published. Required fields are marked *