wp_set_post_terms

Set the terms for a post.

Description

(array|false|WP_Error) wp_set_post_terms( (int) $post_id = 0, (string) $tags = '', (string) $taxonomy = 'post_tag', (bool) $append = false ); 

Returns (array|false|WP_Error)

Array of term taxonomy IDs of affected terms. WP_Error or false on failure.

Parameters (4)

0. $post_id — Optional. (int)
The Post ID. Does not default to the ID of the global $post.
1. $tags — Optional. (string) => ''
An array of terms to set for the post, or a string of terms separated by commas. Default empty.
2. $taxonomy — Optional. (string) => 'post_tag'
Taxonomy name. Default post_tag..
3. $append — Optional. (bool) => false
If true, don't delete existing terms, just add on. If false, replace the terms with the new terms. Default false.

Usage

  1. if ( !function_exists( 'wp_set_post_terms' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // Optional. The Post ID. Does not default to the ID of the global $post. 
  5. $post_id = -1; 
  6.  
  7. // Optional. An array of terms to set for the post, or a string of terms 
  8. // separated by commas. Default empty. 
  9. $tags = ''; 
  10.  
  11. // Optional. Taxonomy name. Default 'post_tag'. 
  12. $taxonomy = 'post_tag'; 
  13.  
  14. // Optional. If true, don't delete existing terms, just add on. If false, 
  15. // replace the terms with the new terms. Default false. 
  16. $append = false; 
  17.  
  18. // NOTICE! Understand what this does before running. 
  19. $result = wp_set_post_terms($post_id, $tags, $taxonomy, $append); 
  20.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/post.php  
  1. function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) { 
  2. $post_id = (int) $post_id; 
  3.  
  4. if ( !$post_id ) 
  5. return false; 
  6.  
  7. if ( empty($tags) ) 
  8. $tags = array(); 
  9.  
  10. if ( ! is_array( $tags ) ) { 
  11. $comma = _x( ', ', 'tag delimiter' ); 
  12. if ( ', ' !== $comma ) 
  13. $tags = str_replace( $comma, ', ', $tags ); 
  14. $tags = explode( ', ', trim( $tags, " \n\t\r\0\x0B, " ) ); 
  15.  
  16. /** 
  17. * Hierarchical taxonomies must always pass IDs rather than names so that 
  18. * children with the same names but different parents aren't confused. 
  19. */ 
  20. if ( is_taxonomy_hierarchical( $taxonomy ) ) { 
  21. $tags = array_unique( array_map( 'intval', $tags ) ); 
  22.  
  23. return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );