Languages: English • Deutsch • Italiano • set object terms 日本語 (Add your language)
Relates an object (post, link etc) to a term and taxonomy type (tag, category, etc). Creates the term and taxonomy relationship if it doesn't already exist.
A relationship means that the term is grouped in or belongs to the taxonomy. A term has no meaning until it is given context by defining which taxonomy it exists under.
<?php wp_set_object_terms( $object_id, $terms, $taxonomy, $append ); ?>
wp-includes/taxonomy.php
If you want to set the categories of a post with the ID of 42:
<?php // An array of IDs of categories we want this post to have. $cat_ids = array( 6, 8 ); /* * If this was coming from the database or another source, we would need to make sure * these were integers: $cat_ids = array_map( 'intval', $cat_ids ); $cat_ids = array_unique( $cat_ids ); */ $term_taxonomy_ids = wp_set_object_terms( 42, $cat_ids, 'category' ); if ( is_wp_error( $term_taxonomy_ids ) ) { // There was an error somewhere and the terms couldn't be set. } else { // Success! The post's categories were set. }
Note that this will set a post's categories to be exactly the array you pass, any categories the post previously had will be removed from the post. See the next example.
If you want to add categories to a post while keeping the categories it has already, you need to pass true for the $append parameter:
<?php // An array of IDs of categories we to add to this post. $cat_ids = array( 6, 8 ); /* * If this was coming from the database or another source, we would need to make sure * these were integers: $cat_ids = array_map( 'intval', $cat_ids ); $cat_ids = array_unique( $cat_ids ); */ // Add these categories, note the last argument is true. $term_taxonomy_ids = wp_set_object_terms( 42, $cat_ids, 'category', true ); if ( is_wp_error( $term_taxonomy_ids ) ) { // There was an error somewhere and the terms couldn't be set. } else { // Success! These categories were added to the post. }
If you want to clear/remove all categories from a post, you can pass an empty value for $terms:
<?php wp_set_object_terms( 42, null, 'category' ); ?>
wp_set_object_terms() is located in wp-includes/taxonomy.php
.