pre_insert_term
Allows you to change a term name (category or tag) before it is sanitized and inserted into the database.
This filter can also stop the term creation operation and display a custom error.
Usage
add_filter( 'pre_insert_term', 'wp_kama_pre_insert_term_filter', 10, 3 );
/**
* Function for `pre_insert_term` filter-hook.
*
* @param string|WP_Error $term The term name to add, or a WP_Error object if there's an error.
* @param string $taxonomy Taxonomy slug.
* @param array|string $args Array or query string of arguments passed to wp_insert_term().
*
* @return string|WP_Error
*/
function wp_kama_pre_insert_term_filter( $term, $taxonomy, $args ){
// filter...
return $term;
}
- $term(string)
- The term name.
- $taxonomy(string)
- The taxonomy name specified as the first parameter of register_taxonomy().
- $args(array/string) (WP 6.1)
- An array or query string of arguments passed to wp_insert_term().
Examples
#1 Change the name of a category being added
The pre_insert_term hook can change the name of a term being created in any way. For example, capitalize the names of all newly created categories:
add_filter( 'pre_insert_term', 'change_pre_insert_term', 10, 2 );
function change_pre_insert_term( $term, $taxonomy ) {
if ( 'category' === $taxonomy ) {
$first_letter = mb_strtoupper( mb_substr( $term, 0, 1 ) );
$remaining_letters = mb_substr( $term, 1 );
$term = $first_letter . $remaining_letters;
}
return $term;
}
#2 Prevent creating categories whose names contain only digits
add_filter( 'pre_insert_term', 'change_pre_insert_term', 10, 2 );
function change_pre_insert_term( $term, $taxonomy ) {
if ( 'category' === $taxonomy && is_numeric( $term ) ) {
return new WP_Error( 'error', 'A category name cannot consist only of digits.' );
}
return $term;
}Changelog
| Since 3.0.0 | Introduced. |
| Since 6.1.0 | The $args parameter was added. |
Where the hook is called
pre_insert_term
wp-includes/taxonomy.php 2475
$term = apply_filters( 'pre_insert_term', $term, $taxonomy, $args );
