wp_set_post_categories

Set categories for a post.

Description

(array|false|WP_Error) wp_set_post_categories( (int) $post_ID = 0, (array) $post_categories = array(), (bool) $append = false ); 

If the post categories parameter is not set, then the default category is going used.

Returns (array|false|WP_Error)

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

Parameters (3)

0. $post_id — Optional. (int)
The Post ID. Does not default to the ID of the global $post. Default 0.
1. $post_categories — Optional. (array) => array()
List of categories or ID of category. Default empty array.
2. $append — Optional. (bool) => false
If true, don't delete existing categories, just add on. If false, replace the categories with the new categories.

Usage

  1. if ( !function_exists( 'wp_set_post_categories' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // Optional. The Post ID. Does not default to the ID 
  5. // of the global $post. Default 0. 
  6. $post_id = -1; 
  7.  
  8. // Optional. List of categories or ID of category. 
  9. // Default empty array. 
  10. $post_categories = array(); 
  11.  
  12. // If true, don't delete existing categories, just add on. 
  13. // If false, replace the categories with the new categories. 
  14. $append = false; 
  15.  
  16. // NOTICE! Understand what this does before running. 
  17. $result = wp_set_post_categories($post_id, $post_categories, $append); 
  18.  

Defined (1)

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

/wp-includes/post.php  
  1. function wp_set_post_categories( $post_ID = 0, $post_categories = array(), $append = false ) { 
  2. $post_ID = (int) $post_ID; 
  3. $post_type = get_post_type( $post_ID ); 
  4. $post_status = get_post_status( $post_ID ); 
  5. // If $post_categories isn't already an array, make it one: 
  6. $post_categories = (array) $post_categories; 
  7. if ( empty( $post_categories ) ) { 
  8. if ( 'post' == $post_type && 'auto-draft' != $post_status ) { 
  9. $post_categories = array( get_option('default_category') ); 
  10. $append = false; 
  11. } else { 
  12. $post_categories = array(); 
  13. } elseif ( 1 == count( $post_categories ) && '' == reset( $post_categories ) ) { 
  14. return true; 
  15.  
  16. return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );