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.

wp_set_object_terms() 描述


 <?php wp_set_object_terms$object_id$terms$taxonomy$append ); ?> 

wp_set_object_terms() 用法



(int) (必填) The object to relate to, such as post ID.

默认值: None


(array/int/string) (必填) The slug or id of the term (such as category or tag IDs), will replace all existing related terms in this taxonomy. To clear or remove all terms from an object, pass an empty string or NULL. Integers are interpreted as tag IDs. Warning: some functions may return term_ids as strings which will be interpreted as slugs consisting of numeric characters!

默认值: None


(array/string) (必填) The context in which to relate the term to the object. This can be category, post_tag, or the name of another taxonomy.

默认值: None


(bool) (可选) If true, tags will be appended to the object. If false, tags will replace existing tags

默认值: False

wp_set_object_terms() 参数


Setting a Post's Categories

If you want to set the categories of a post with the ID of 42:

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.

Adding Categories to a Post

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:

Removing All Categories From a Post

If you want to clear/remove all categories from a post, you can pass an empty value for $terms:

wp_set_object_terms() 示例


  • wp_set_object_terms() does not check if there is a a relationship between the object (=post type) and the taxonomy (like post_tag, category or a custom taxonomy). Because of that, any existing term will be paired with the object, whether or not there is a connection between the object and the taxonomy (of this particular term)!! ( Further information in german)
  • 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.
  • It may be confusing but the returned array consists of term_taxonomy_ids instead of term_ids.

wp_set_object_terms() 注意


wp_set_object_terms() 历史


wp_set_object_terms() 函数的代码位于 wp-includes/taxonomy.php.

wp_set_object_terms() 源文件