Codex tools: Log in
Contents |
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 ) ?>
If you wanted to add a categories to a post with the ID of 42:
<?php
$cat_ids = array( 6,8 );
//to make sure the terms IDs is integers:
//$cat_ids = array_map('intval', $cat_ids);
//$cat_ids = array_unique( $cat_ids );
wp_set_object_terms( '42', $cat_ids, 'category' );
?>
If you wanted to clear/remove all categories from a post with the ID of 42:
<?php wp_set_object_terms( '42', NULL, 'category' ); ?>
Perhaps the wp_set_post_terms() is a more useful function, since it checks the values, converting taxonomies separated by commas and validating hierarchical terms in integers.
wp_set_object_terms() is located in wp-includes/taxonomy.php.