Set taxonomy slug as taxonomy title

With post types I can easily set the slug to be always identical to the post type title.

add_filter( 'wp_insert_post_data', 'prefix_wp_insert_post_data' );
function prefix_wp_insert_post_data( $data ) {
    $data['post_name'] = sanitize_title( $data['post_title'] );
    return $data;
}

But with taxonomies I’m rather stuck.
I’ve been reading up on the editable_slug and wp_insert_post filters and this trac ticket https://core.trac.wordpress.org/ticket/9073, but still unsure on how to accomplish the same.

Could someone perhaps point me into an even more novice direction?

1 Answer
1

The terms are inserted with wp_insert_term() and updated with wp_update_term().

There’s the pre_insert_term filter, where one can modify the term’s name but not the slug.

If we dig further, we see that both functions call sanitize_term() that again calls the sanitize_term_field() function.

There we have various filters available.

Example #1

Here’s one combination if we want to target the category taxonomy during inserts:

/**
 * Set the category slug as the sanitize category name during category inserts
 */
add_filter( 'pre_category_name', function( $name )
{
    add_filter( 'pre_category_slug', function( $slug ) use ( $name )
    {       
        return $name ? sanitize_title( $name ) : $slug;
    } );

    return $name;
} );

Example #2

Let’s instead wrap it inside the pre_insert_term hook and make sure it only runs once.

/**
 * Set the term's slug as the sanitized term's name when inserting category terms
 */
add_filter( 'pre_insert_term', function( $term, $taxonomy )
{
    add_filter( 'pre_term_slug', function( $value ) use ( $term, $taxonomy )
    {       
        if( ! did_action( 'pre_term_slug' ) && $term && 'category' === $taxonomy )
            $value = sanitize_title( $term );

        return $value;
    } );

    return $term;
}, 10, 2 );

To target the term’s update, we can use the edit_category_name and edit_category_slug filters, or in general the edit_term_name and edit_term_slug filters.

Hopefully you can adjust it and test it further.

Leave a Comment