Sets the terms for a post.
Description
See also
Parameters
$post_id
intoptional- The Post ID. Does not default to the ID of the global $post.
$terms
string|arrayoptional- An array of terms to set for the post, or a string of terms separated by commas. Hierarchical taxonomies must always pass IDs rather than names so that children with the same names but different parents aren’t confused.
Default:
''
$taxonomy
stringoptional- Taxonomy name. Default
'post_tag'
.Default:
'post_tag'
$append
booloptional- If true, don’t delete existing terms, just add on. If false, replace the terms with the new terms.
Default:
false
Source
function wp_set_post_terms( $post_id = 0, $terms = '', $taxonomy = 'post_tag', $append = false ) {
$post_id = (int) $post_id;
if ( ! $post_id ) {
return false;
}
if ( empty( $terms ) ) {
$terms = array();
}
if ( ! is_array( $terms ) ) {
$comma = _x( ',', 'tag delimiter' );
if ( ',' !== $comma ) {
$terms = str_replace( $comma, ',', $terms );
}
$terms = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
}
/*
* Hierarchical taxonomies must always pass IDs rather than names so that
* children with the same names but different parents aren't confused.
*/
if ( is_taxonomy_hierarchical( $taxonomy ) ) {
$terms = array_unique( array_map( 'intval', $terms ) );
}
return wp_set_object_terms( $post_id, $terms, $taxonomy, $append );
}
Changelog
Version | Description |
---|---|
2.8.0 | Introduced. |
Non hierarchical term example
For non-hierarchical terms (such as tags), you can pass either the term name or id. If you pass the id there is only one caveat: You must pass it as an integer, and it must be in an array. This is necessary because any non-array value passed will be converted to a string, which will be interpreted as a term name.
This function will only work on the native post type. For a taxonomy on a custom post type use wp_set_object_terms()
I do not know why, but you need to wrap your term_id in Array ((int) $ Term_id) – Then it will work as id … otherwise it is to create a term with name = $ Term_id
Hierarchical term example
For hierarchical terms (such as categories), you must always pass the id rather than the term name to avoid confusion where there may be another child with the same name.
To get the term id you can use:
You may also need to pass by reference:
wp_set_post_terms( $post_id, $term_id, $taxonomy );
To show you are passing the term ID from line above. Also term_exists will return an array so you need to specify the ID as specified in term_exists examples. And the ampersand seems like a typo.