Create, update and assign terms in code: wp_insert_term() and wp_set_post_terms()
Imports and migrations need to create categories and other terms in code, often with a hierarchy, and then assign them to posts. WordPress has functions for both: wp_insert_term(), wp_update_term() and wp_delete_term() manage the terms, wp_set_post_terms() and wp_set_object_terms() attach them to posts. The details that matter are what happens when a term already exists and whether assigning replaces or adds terms.
Problem: An import reads product categories with parents from a CSV file, must create missing ones, update descriptions of existing ones, assign them to products, and give the same result when it runs twice.
Solution: Look the term up with term_exists() (with the parent), update it with wp_update_term() or create it with wp_insert_term(), treat a term_exists error as “found”, and assign the IDs with wp_set_object_terms(), choosing between replacing and appending.
Create or update a term
<?php
function ha_upsert_term( $name, $taxonomy, $args = array() ) {
$parent = isset( $args['parent'] ) ? (int) $args['parent'] : 0;
$existing = term_exists( $name, $taxonomy, $parent );
if ( $existing ) {
$term_id = (int) $existing['term_id'];
$result = wp_update_term( $term_id, $taxonomy, $args );
return is_wp_error( $result ) ? $result : $term_id;
}
$result = wp_insert_term( $name, $taxonomy, $args );
if ( is_wp_error( $result ) ) {
// A term with this name already exists under this parent
if ( 'term_exists' === $result->get_error_code() ) {
return (int) $result->get_error_data( 'term_exists' );
}
return $result;
}
return (int) $result['term_id']; // array( 'term_id' => ..., 'term_taxonomy_id' => ... )
}
$parent = ha_upsert_term( 'Electronics', 'product_cat', array( 'slug' => 'electronics', 'description' => 'All electronics' ) );
if ( ! is_wp_error( $parent ) ) {
$phones = ha_upsert_term( 'Smartphones', 'product_cat', array( 'slug' => 'smartphones', 'parent' => $parent ) );
}
In hierarchical taxonomies a name has to be unique only among the children of the same parent: “Accessories” can exist under “Phones” and under “Laptops”. Slugs are unique in the whole taxonomy, so WordPress adds -2 to the second one unless you pass your own slug.
Assigning terms to a post
<?php // Replace all categories of the post with these (term IDs as integers) wp_set_object_terms( $post_id, array( 12, 15 ), 'product_cat' ); // Add a term, keep the existing ones wp_set_object_terms( $post_id, array( 20 ), 'product_cat', true ); // Tags by name: missing tags are created wp_set_object_terms( $post_id, array( 'wireless', 'bluetooth' ), 'product_tag' ); // Remove all terms of a taxonomy from the post wp_set_object_terms( $post_id, array(), 'product_cat' );
wp_set_post_terms( $post_id, $terms, $taxonomy, $append ) is the post-specific wrapper. For hierarchical taxonomies it expects term IDs, and a numeric string like "12" passed to wp_set_object_terms() is treated as a name, which creates a new term called “12”. Cast IDs with array_map( 'intval', $ids ) before passing them.
Deleting
<?php // Posts that had only this category get the default term instead wp_delete_term( $phones, 'product_cat', array( 'default' => $parent, 'force_default' => true ) );
Large imports
Term counts are updated after every assignment. For thousands of posts, defer it and update once at the end:
<?php wp_defer_term_counting( true ); // ... the import loop ... wp_defer_term_counting( false ); // recounts the deferred terms
How to create the posts themselves is shown in creating and updating posts with wp_insert_post(), and how to store extra data on terms in term meta.
NOTE: Strings from external data become term names directly. Clean them (sanitize_text_field(), trimmed, consistent case) before passing them, otherwise “Phones”, “phones” and “Phones ” in a CSV create three different terms.