Exciting News! Flipper Code is now WePlugins! Same commitment to excellence, brand new identity.

How to use pre_insert_term filter in WordPress

Sandeep Kumar Mishra
Sandeep Kumar Mishra
June 12, 2023
5 minutes read

 

Have you ever wanted to customize the way terms are inserted into your WordPress database? Well, the pre_insert_term filter is here to help! This nifty hook lets you modify a term before it’s sanitized and added to the database. You can use this hook by registering it with add_filter in your theme’s functions.php file or better yet, in a custom WordPress Plugin. At WePlugins, we always recommend creating a custom plugin to keep your customizations safe during theme updates.

Sometimes, you might even need to remove a registered hook, and that’s where remove_filter comes into play.

Parameters

Below are the 2 parameters required to use this hook:

  • $term : (string|WP_Error) The term name to add, or a WP_Error object if there’s an error.
  • $taxonomy : (string) Taxonomy slug.

Live Example 1: Basic Usage

Let’s see how you can use the pre_insert_term hook to modify a term before insertion.

    function weplugins_modify_pre_insert_term_defaults($term, $taxonomy) { 
        // Update the $term variable according to your website requirements and return this variable.
        return $term; 
    }
    // add the filter
    add_filter( "pre_insert_term", "weplugins_modify_pre_insert_term_defaults", 10, 2 );
    

Live Example 2: Conditional Modification

Here’s how you can conditionally change the term based on the taxonomy.

    function weplugins_conditional_modify_term($term, $taxonomy) { 
        if ($taxonomy == 'category') {
            $term = 'Modified Category Term';
        }
        return $term; 
    }
    // add the filter
    add_filter( "pre_insert_term", "weplugins_conditional_modify_term", 10, 2 );
    

Live Example 3: Removing a Hook

To remove a hook callback, use the example below. Make sure to provide the same callback function name, priority, and number of arguments while removing the hook callback.

    remove_filter( "pre_insert_term", "weplugins_modify_pre_insert_term_defaults", 10, 2 );
    

Access Premium WordPress Plugins

Contact Us

If you’re having any trouble using this hook or need some customization, feel free to contact us. We’re here to help!

 

Sandeep Kumar Mishra

Sandeep Kumar Mishra

Sandeep Kumar Mishra writes about WordPress and Artificial Intelligence, offering tips and guides to help you master your website and stay updated with the latest tech trends.

Explore the latest in WordPress

Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.