Custom code for adding a custom taxonomy to WordPress

Emily T Dec 17, 2024 Taxonomies
How can I group my blog posts into different categories that I create myself?
How can I register a custom taxonomy in WordPress using the register_taxonomy function for better content organization?
Andy answered Dec 17, 2024

Adding a Custom Taxonomy in WordPress

Custom Code Solution

This code creates a new custom taxonomy called "Topics" for your blog posts. Place this code in your theme's functions.php file or in a site-specific plugin:

Register the custom taxonomy:

function create_topics_taxonomy() {
    $labels = array(
        'name'              => 'Topics',
        'singular_name'     => 'Topic',
        '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'
    );

    $args = array(
        'labels'            => $labels,
        'hierarchical'      => true, // Set to false if you want tag-like behavior
        'public'            => true,
        'show_ui'          => true,
        'show_admin_column' => true,
        'show_in_rest'     => true, // Enable Gutenberg support
        'query_var'        => true,
        'rewrite'          => array('slug' => 'topic')
    );

    register_taxonomy('topic', array('post'), $args);
}
add_action('init', 'create_topics_taxonomy');

Code Customization

To modify this code for your needs:

  1. Change 'topic' to your desired taxonomy name
  2. Adjust the 'labels' array text
  3. Change the 'slug' in rewrite array
  4. Modify 'hierarchical' to false if you want tag-like behavior instead of categories

Plugin Alternative

If you prefer using a plugin, here are reliable options:

  1. Custom Post Type UI - User-friendly interface for creating taxonomies
  2. Pods - Advanced content type and field management

Usage After Implementation

Once implemented, you can:

  1. Find "Topics" in your WordPress admin menu
  2. Add new topics like regular categories
  3. Assign topics to posts while editing
  4. Filter posts by topics in the admin area
  5. Use WordPress functions like get_terms() to display topics on your site

Query Example

To display posts from a specific topic:

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'topic',
            'field'    => 'slug',
            'terms'    => 'your-topic-slug'
        )
    )
);
$query = new WP_Query($args);