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?


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.

  • Thank you for explaining this in detail. This definitely gives me something to work with. – user5424 Nov 12 '15 at 18:25
  • You're welcome, good luck with the project @CorvanNoorloos – birgire Nov 12 '15 at 18:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy