Codex tools: Log in
Languages: English • 日本語 • Türkçe • (Add your language)
Contents |
This function updates posts (and pages) in the database. To work as expected, it is necessary to pass the ID of the post to be updated.
Note that when the post is "updated", the existing Post record is duplicated for audit/revision purposes. The primary record is then updated with the new values. Category associations, custom fields, post meta, and other related entries continue to be linked to the primary Post record.
<?php wp_update_post( $post ); ?>
Before calling wp_update_post() it is necessary to create an array to pass the necessary elements. Unlike wp_insert_post(), it is only necessary to pass the ID of the post to be updated and the elements to be updated. The names of the elements should match those in the database.
// Update 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 );
Categories need to be passed as an array of integers that match the category IDs in the database. This is the case even where only one category is assigned to the post.
When executed by an action hooked into save_post (e.g. a custom metabox), wp_update_post() has the potential to create an infinite loop. This happens because (1) wp_update_post() results in save_post being fired and (2) save_post is called twice when revisions are enabled (first when creating the revision, then when updating the original post—resulting in the creation of endless revisions).
If you must update a post from code called by save_post, make sure to verify the post_type is not set to 'revision' and that the $post object does indeed need to be updated.
Likewise, an action hooked into edit_attachment can cause an infinite loop if it contains a function call to wp_update_post passing an array parameter with a key value of "ID" and an associated value that corresponds to an Attachment.
Note you will need to remove then add the hook, code sample modified from the API/Action ref. [save_posts](http://codex.wordpress.org/Plugin_API/Action_Reference/save_post)
<?php
function my_function(){
if ( ! wp_is_post_revision( $post_id ) ){
// unhook this function so it doesn't loop infinitely
remove_action('save_post', 'my_function');
// update the post, which calls save_post again
wp_update_post( $my_args );
// re-hook this function
add_action('save_post', 'my_function');
}
}
add_action('save_posts', 'my_function');
?>
If you are trying to use wp_update_post() to schedule an existing draft, it will not work unless you pass $my_post->edit_date = true. WordPress will ignore the post_date when updating drafts unless edit_date is true.
wp_update_post() is located in wp-includes/post.php.