Updating a Post in WordPress Using wp_update_post

The WordPress wp_update_post function is used to update an existing post in the WordPress database. This function can be useful for making changes to a post’s content, title, status, or any other post-related data without having to manually edit the database.

By using the wp_update_post function, developers can programmatically update posts on their WordPress site, allowing for automation of certain tasks or bulk updates to multiple posts at once.

The wp_update_post function provides a convenient way to modify post data within WordPress, making it a valuable tool for developers working with WordPress websites.

Parameters Accepted by wp_update_post Function

  • $postarr (array/object, optional, default: array()): Post data. Arrays should be escaped, while objects should not be. See wp_insert_post() for accepted arguments. Default value is an empty array.
  • $wp_error (boolean, optional, default: false): Whether to return a WP_Error on failure.
  • $fire_after_hooks (boolean, optional, default: true): Whether to fire the after insert hooks.

Value Returned by wp_update_post Function

The function returns an int representing the post ID on success. On failure, it returns the value 0 or a WP_Error.

Examples

How to update a post’s title using wp_update_post

Here’s a code snippet to update a post’s title using the wp_update_post function:

$post_id = 123;
$post_data = array(
 'ID' => $post_id,
 'post_title' => 'New Post Title'
);
wp_update_post( $post_data );

This code snippet updates the title of the post with ID 123 to “New Post Title” using the wp_update_post function.

How to update a post’s content using wp_update_post

Here’s a code snippet to update a post’s content using the wp_update_post function:

$post_id = 456;
$post_data = array(
 'ID' => $post_id,
 'post_content' => 'New post content'
);
wp_update_post( $post_data );

This code snippet updates the content of the post with ID 456 to “New post content” using the wp_update_post function.

How to update a post’s status using wp_update_post

Here’s a code snippet to update a post’s status using the wp_update_post function:

$post_id = 789;
$post_data = array(
 'ID' => $post_id,
 'post_status' => 'draft'
);
wp_update_post( $post_data );

This code snippet updates the status of the post with ID 789 to “draft” using the wp_update_post function.

Conclusion

In conclusion, the wp_update_post function is an useful component for developers working with WordPress. It allows for easy and efficient updating of post content, status, and other parameters, streamlining the process of managing and maintaining a website. By understanding how to properly utilize this function, developers can ensure their WordPress sites are up-to-date and functioning at their best. With its flexibility and versatility, wp_update_post is an essential function for any WordPress developer’s toolkit.

Related WordPress Functions