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.