wp_update_post

Update a post with new post data.

Description

(int|WP_Error) wp_update_post( (array) $postarr = array(), (bool) $wp_error = false ); 

The date does not have to be set for drafts. You can set the date and it will not be overridden.

Returns (int|WP_Error)

The value 0 or WP_Error on failure. The post ID on success.

Parameters (2)

0. $postarr — Optional. (array) => array()
Post data. Arrays are expected to be escaped, objects are not. Default array.
1. $wp_error — Optional. (bool) => false
Allow return of WP_Error on failure. Default false.

Usage

  1. if ( !function_exists( 'wp_update_post' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // Optional. Post data. Arrays are expected to be escaped, 
  5. // objects are not. Default array. 
  6. $postarr = array(); 
  7.  
  8. // Optional. Allow return of WP_Error on failure. Default false. 
  9. $wp_error = false; 
  10.  
  11. // NOTICE! Understand what this does before running. 
  12. $result = wp_update_post($postarr, $wp_error); 
  13.  

Defined (1)

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

/wp-includes/post.php  
  1. function wp_update_post( $postarr = array(), $wp_error = false ) { 
  2. if ( is_object($postarr) ) { 
  3. // Non-escaped post was passed. 
  4. $postarr = get_object_vars($postarr); 
  5. $postarr = wp_slash($postarr); 
  6.  
  7. // First, get all of the original fields. 
  8. $post = get_post($postarr['ID'], ARRAY_A); 
  9.  
  10. if ( is_null( $post ) ) { 
  11. if ( $wp_error ) 
  12. return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) ); 
  13. return 0; 
  14.  
  15. // Escape data pulled from DB. 
  16. $post = wp_slash($post); 
  17.  
  18. // Passed post category list overwrites existing category list if not empty. 
  19. if ( isset($postarr['post_category']) && is_array($postarr['post_category']) 
  20. && 0 != count($postarr['post_category']) ) 
  21. $post_cats = $postarr['post_category']; 
  22. else 
  23. $post_cats = $post['post_category']; 
  24.  
  25. // Drafts shouldn't be assigned a date unless explicitly done so by the user. 
  26. if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) && 
  27. ('0000-00-00 00:00:00' == $post['post_date_gmt']) ) 
  28. $clear_date = true; 
  29. else 
  30. $clear_date = false; 
  31.  
  32. // Merge old and new fields with new fields overwriting old ones. 
  33. $postarr = array_merge($post, $postarr); 
  34. $postarr['post_category'] = $post_cats; 
  35. if ( $clear_date ) { 
  36. $postarr['post_date'] = current_time('mysql'); 
  37. $postarr['post_date_gmt'] = ''; 
  38.  
  39. if ($postarr['post_type'] == 'attachment') 
  40. return wp_insert_attachment($postarr); 
  41.  
  42. return wp_insert_post( $postarr, $wp_error );