WordPress更新文章函数:wp_update_post


【描述】
该函数用于更新数据库中的文章。如希望函数正常运行,必须传递将被更新的文章编号ID。
【使用方法】

  1. <?php wp_update_post( $post ); ?>

【例子】
调用wp_update_post( )前需创建一个数组以传递必要元素。与 wp_insert_post()不同的是,这里只需要传递将更新的文章编号和元素。元素名称应与数据库中名称相匹配。

  1. // 更新编号为37的文章
  2. $my_post = array();
  3. $my_post['ID'] = 37;
  4. $my_post['post_content'] = 'This is the updated content.';
  5.  
  6. // Update the post into the database
  7. wp_update_post( $my_post );

【类别】
需要将类别作为整数数组传递,该数组应与数据库中的类别编号相匹配。即使文章只属于某一项类别,情况也应如此。

【参数】
$post

(数组)(可选)能表示可组成文章元素的对象。这些元素与数据库wp_posts表格中的纵列名称应一一对应。可以不填充ID(编号)字段,这样的话使用该函数几乎没有任何意义。

默认值:一个空数组

【返回的值】
若文章成功加入数据库,返回文章编号。否则返回0.

【相关函数】

  1. wp_insert_post()

【源文件】
wp_update_post() 位于 wp-includes/post.php.

  1. /**
  2. * Update a post with new post data.
  3. *
  4. * The date does not have to be set for drafts. You can set the date and it will
  5. * not be overridden.
  6. *
  7. * @since 1.0.0
  8. *
  9. * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
  10. * @return int 0 on failure, Post ID on success.
  11. */
  12. function wp_update_post($postarr = array()) {
  13. if ( is_object($postarr) ) {
  14. // non-escaped post was passed
  15. $postarr = get_object_vars($postarr);
  16. $postarr = add_magic_quotes($postarr);
  17. }
  18.  
  19. // First, get all of the original fields
  20. $post = wp_get_single_post($postarr['ID'], ARRAY_A);
  21.  
  22. // Escape data pulled from DB.
  23. $post = add_magic_quotes($post);
  24.  
  25. // Passed post category list overwrites existing category list if not empty.
  26. if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
  27. && 0 != count($postarr['post_category']) )
  28. $post_cats = $postarr['post_category'];
  29. else
  30. $post_cats = $post['post_category'];
  31.  
  32. // Drafts shouldn't be assigned a date unless explicitly done so by the user
  33. if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
  34. ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
  35. $clear_date = true;
  36. else
  37. $clear_date = false;
  38.  
  39. // Merge old and new fields with new fields overwriting old ones.
  40. $postarr = array_merge($post, $postarr);
  41. $postarr['post_category'] = $post_cats;
  42. if ( $clear_date ) {
  43. $postarr['post_date'] = current_time('mysql');
  44. $postarr['post_date_gmt'] = '';
  45. }
  46.  
  47. if ($postarr['post_type'] == 'attachment')
  48. return wp_insert_attachment($postarr);
  49.  
  50. return wp_insert_post($postarr);
  51. }