Using WordPress ‘pre_term_{$field}’ PHP filter

“pre_term_{$field}” is a dynamic WordPress filter that allows you to modify a term field value before it is sanitized in WordPress.

This filter is especially helpful when you need to customize the behavior of term fields in specific taxonomies.

Usage

function my_custom_pre_term_field( $value, $taxonomy ) {
    // Your custom code here
    return $modified_value;
}
add_filter( "pre_term_{$field}", 'my_custom_pre_term_field', 10, 2 );

Parameters

  • $value (mixed): The original value of the term field.
  • $taxonomy (string): The taxonomy slug associated with the term.

Examples

Change the term name to uppercase for a specific taxonomy.

function uppercase_term_name( $value, $taxonomy ) {
    if ( 'custom_taxonomy' === $taxonomy ) {
        return strtoupper( $value );
    }
    return $value;
}
add_filter( 'pre_term_name', 'uppercase_term_name', 10, 2 );

Explanation: This code checks if the taxonomy is custom_taxonomy and converts the term name to uppercase if it is. Otherwise, it returns the original value.

Add a prefix to the term description for a specific taxonomy.

function add_prefix_to_term_description( $value, $taxonomy ) {
    if ( 'product_category' === $taxonomy ) {
        return 'Product Category: ' . $value;
    }
    return $value;
}
add_filter( 'pre_term_description', 'add_prefix_to_term_description', 10, 2 );

Explanation: This code checks if the taxonomy is product_category and adds a prefix to the term description if it is. Otherwise, it returns the original value.

Append a custom string to term slug for a specific taxonomy.

function append_string_to_term_slug( $value, $taxonomy ) {
    if ( 'event_category' === $taxonomy ) {
        return $value . '-event';
    }
    return $value;
}
add_filter( 'pre_term_slug', 'append_string_to_term_slug', 10, 2 );

Explanation: This code checks if the taxonomy is event_category and appends -event to the term slug if it is. Otherwise, it returns the original value.

Sanitize term name using a custom function for a specific taxonomy.

function custom_sanitize_term_name( $value, $taxonomy ) {
    if ( 'book_genre' === $taxonomy ) {
        return my_custom_sanitization_function( $value );
    }
    return $value;
}
add_filter( 'pre_term_name', 'custom_sanitize_term_name', 10, 2 );

Explanation: This code checks if the taxonomy is book_genre and applies a custom sanitization function to the term name if it is. Otherwise, it returns the original value.

Modify term parent ID for a specific taxonomy.

function change_term_parent_id( $value, $taxonomy ) {
    if ( 'location' === $taxonomy && 5 === $value ) {
        return 10;
    }
    return $value;
}
add_filter( 'pre_term_parent', 'change_term_parent_id', 10, 2 );

Explanation: This code checks if the taxonomy is location and if the term parent ID is 5. If both conditions are met, it changes the term parent ID to 10. Otherwise, it returns the original value.