WordPress create term programmatically with wp_insert_term

(array|WP_Error) wp_insert_term( $term, $taxonomy, $args = array() );

A non-existent term is inserted in the following sequence: 1. The term is added to the term table, then related to the taxonomy. 2. If everything is correct, several actions are fired. 3. The term_id_filter is evaluated. 4. The term cache is cleaned. 5. Several more actions are fired. 6. An array is returned containing the term_id and term_taxonomy_id.

If the slug argument is not empty, then it is checked to see if the term is invalid. If it is not a valid, existing term, it is added and the term_id is given.

If the taxonomy is hierarchical, and the parent argument is not empty, the term is inserted and the term_id will be given.

Error handling: If $taxonomy does not exist or $term is empty, a WP_Error object will be returned.

If the term already exists on the same hierarchical level, or the term slug and name are not unique, a WP_Error object will be returned.

Examples code

if ( !function_exists( 'wp_insert_term' ) ) { 
    require_once ABSPATH . WPINC . '/taxonomy.php'; 
// The term to add or update. 
$term = ''; 
// The taxonomy to which to add the term. 
$taxonomy = ''; 
// Optional. Array or string of arguments for inserting a term. 
$args = array( 
    'alias_of' => '', 
    'description' => string, 
    'parent' => 0 
// NOTICE! Understand what this does before running. 
$result = wp_insert_term($term, $taxonomy, $args);


Leave a Reply

Your email address will not be published. Required fields are marked *