search ]

Register Multiple Taxonomies in One Function

When working on a project that requires creating multiple taxonomies, it makes sense to use this function rather than creating a separate function for each taxonomy. Put each taxonomy’s parameters in the array and the function handles the rest:

<?php
/**
 * Register Multiple Taxonomies
 *
 */
function register_multiple_taxonomies() {
    $taxonomies = array(
        array(
            'slug'         => 'job-department',
            'single_name'  => 'Department',
            'plural_name'  => 'Departments',
            'post_type'    => 'jobs',
            'rewrite'      => array( 'slug' => 'department' ),
        ),
        array(
            'slug'         => 'job-type',
            'single_name'  => 'Type',
            'plural_name'  => 'Types',
            'post_type'    => 'jobs',
            'hierarchical' => false,
        ),
        array(
            'slug'         => 'job-experience',
            'single_name'  => 'Min-Experience',
            'plural_name'  => 'Min-Experiences',
            'post_type'    => 'jobs',
        ),
    );
    foreach( $taxonomies as $taxonomy ) {
        $labels = array(
            'name' => $taxonomy['plural_name'],
            'singular_name' => $taxonomy['single_name'],
            'search_items' =>  'Search ' . $taxonomy['plural_name'],
            'all_items' => 'All ' . $taxonomy['plural_name'],
            'parent_item' => 'Parent ' . $taxonomy['single_name'],
            'parent_item_colon' => 'Parent ' . $taxonomy['single_name'] . ':',
            'edit_item' => 'Edit ' . $taxonomy['single_name'],
            'update_item' => 'Update ' . $taxonomy['single_name'],
            'add_new_item' => 'Add New ' . $taxonomy['single_name'],
            'new_item_name' => 'New ' . $taxonomy['single_name'] . ' Name',
            'menu_name' => $taxonomy['plural_name']
        );
        
        $rewrite = isset( $taxonomy['rewrite'] ) ? $taxonomy['rewrite'] : array( 'slug' => $taxonomy['slug'] );
        $hierarchical = isset( $taxonomy['hierarchical'] ) ? $taxonomy['hierarchical'] : true;
    
        register_taxonomy( $taxonomy['slug'], $taxonomy['post_type'], array(
            'hierarchical' => $hierarchical,
            'labels' => $labels,
            'show_ui' => true,
            'query_var' => true,
            'rewrite' => $rewrite,
        ));
    }
    
}
add_action( 'init', 'register_multiple_taxonomies' );
Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo