Can’t custom taxonomies have same terms (slugs) as categories?

Turns out, this is a bug in the core. I was about to report it, but found out that it’s been there for, like years, and applies to custom taxonomies as well. See tickets: #5809, #21950 and #22023.

If all goes as planned, it’s set to be fixed in 3.8 3.9 4.1 4.2. UPDATE: Yep, fixed!


In the meantime, here’s a plan to overcome the issue — automatically set a custom slug suffix for all newly created terms under a taxonomy:

/*
 * Set custom slug suffix for terms of a taxonomy
 * 
 * http://wordpress.stackexchange.com/q/42550/10691
 * http://wordpress.stackexchange.com/q/71304/10691
 * http://wordpress.stackexchange.com/q/120096/10691
 * https://github.com/WordPress/WordPress/blob/master/wp-includes/taxonomy.php
 */
add_action( 'created_term', 'aahank_add_suffix_to_term', 10, 3 );
function aahank_add_suffix_to_term( $term_id, $tt_id, $taxonomy ) {
    if( $taxonomy == 'book' ) {

        // e.g. Term name 'PHP' and term slug 'php-books'
        $term = get_term( $term_id, $taxonomy );
        $args = array( 'slug' => $term->slug . '-books' );
        wp_update_term( $term_id, $taxonomy, $args );

    }
}

This isn’t retrospective, i.e. slugs of only the new terms under the taxonomy (‘books’ in our case) are created with our custom suffix (‘-books’).

To set a prefix instead, change this line in the function:

$args = array( 'slug' => $term->slug . '-books' );

to something like this:

// e.g. Term name 'PHP' and term slug 'books-php'
$args = array( 'slug' => 'books-' . $term->slug );

And once the bug is fixed…

Dump the database and do a regex search and replace using a proper text editor like Sublime Text or TextMate (or like this).

Probably not the best way to do it, but good enough to get the job done.

Leave a Comment