Using WordPress ‘pre_insert_term’ PHP filter

The pre_insert_term filter allows you to modify a term before it is sanitized and inserted into the WordPress database.

Usage

add_filter('pre_insert_term', 'your_custom_function', 10, 3);
function your_custom_function($term, $taxonomy, $args) {
    // your custom code here
    return $term;
}

Parameters

  • $term (string|WP_Error): The term name to add, or a WP_Error object if there’s an error.
  • $taxonomy (string): Taxonomy slug.
  • $args (array|string): Array or query string of arguments passed to wp_insert_term().

More information

See WordPress Developer Resources: https://developer.wordpress.org/reference/hooks/pre_insert_term/

Examples

Uppercase all terms before insertion

This example changes all terms to uppercase before insertion.

add_filter('pre_insert_term', 'uppercase_term', 10, 3);
function uppercase_term($term, $taxonomy, $args) {
    $term = strtoupper($term);
    return $term;
}

Append a custom string to term names

This example appends a custom string ‘-CUSTOM’ to term names before insertion.

add_filter('pre_insert_term', 'append_custom_string', 10, 3);
function append_custom_string($term, $taxonomy, $args) {
    $term .= '-CUSTOM';
    return $term;
}

Prevent insertion of terms with certain keywords

This example prevents terms containing the keyword ‘forbidden’ from being inserted.

add_filter('pre_insert_term', 'prevent_forbidden_terms', 10, 3);
function prevent_forbidden_terms($term, $taxonomy, $args) {
    if (strpos(strtolower($term), 'forbidden') !== false) {
        return new WP_Error('term_not_allowed', 'The term contains a forbidden keyword.');
    }
    return $term;
}

Limit term length

This example limits term length to a maximum of 20 characters.

add_filter('pre_insert_term', 'limit_term_length', 10, 3);
function limit_term_length($term, $taxonomy, $args) {
    if (strlen($term) > 20) {
        $term = substr($term, 0, 20);
    }
    return $term;
}

Replace specific words before insertion

This example replaces the word ‘apple’ with ‘orange’ before term insertion.

add_filter('pre_insert_term', 'replace_specific_word', 10, 3);
function replace_specific_word($term, $taxonomy, $args) {
    $term = str_replace('apple', 'orange', $term);
    return $term;
}