dd

WordPress更新文章函数:wp_update_post


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

  <?php wp_update_post( $post ); ?>

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

// 更新编号为37的文章
  $my_post = array();
  $my_post['ID'] = 37;
  $my_post['post_content'] = 'This is the updated content.';

// Update the post into the database
  wp_update_post( $my_post );

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

【参数】
$post

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

默认值:一个空数组

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

【相关函数】

wp_insert_post()

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

/**
 * Update a post with new post data.
 *
 * The date does not have to be set for drafts. You can set the date and it will
 * not be overridden.
 *
 * @since 1.0.0
 *
 * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
 * @return int 0 on failure, Post ID on success.
 */
function wp_update_post($postarr = array()) {
 if ( is_object($postarr) ) {
  // non-escaped post was passed
  $postarr = get_object_vars($postarr);
  $postarr = add_magic_quotes($postarr);
 }

 // First, get all of the original fields
 $post = wp_get_single_post($postarr['ID'], ARRAY_A);

 // Escape data pulled from DB.
 $post = add_magic_quotes($post);

 // Passed post category list overwrites existing category list if not empty.
 if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
    && 0 != count($postarr['post_category']) )
  $post_cats = $postarr['post_category'];
 else
  $post_cats = $post['post_category'];

 // Drafts shouldn't be assigned a date unless explicitly done so by the user
 if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
    ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
  $clear_date = true;
 else
  $clear_date = false;

 // Merge old and new fields with new fields overwriting old ones.
 $postarr = array_merge($post, $postarr);
 $postarr['post_category'] = $post_cats;
 if ( $clear_date ) {
  $postarr['post_date'] = current_time('mysql');
  $postarr['post_date_gmt'] = '';
 }

 if ($postarr['post_type'] == 'attachment')
  return wp_insert_attachment($postarr);

 return wp_insert_post($postarr);
}