wp_update_post

Home » Functions » wp_update_post

The wp_update_post function is a core WordPress function designed to update an existing post or page in the database. It takes an array of arguments that define the updated post or page and returns the ID of the updated post.

This function allows developers to programmatically update posts and pages without having to go through the WordPress admin dashboard. Some examples of when this function might be useful include updating post metadata, changing a post’s status or visibility, or updating the post content itself.

Here is an example usage code:

$post_id = 123; // ID of the post to update

// Define the updated post arguments
$post_args = array(
    'post_title' => 'New Post Title',
    'post_content' => 'New post content goes here',
    'post_status' => 'publish'
);

// Update the post with the new arguments
wp_update_post( $post_args, true );

// Check if the update was successful
if ( ! is_wp_error( $post_id ) ) {
    echo 'Post updated successfully!';
} else {
    echo 'Error updating post: ' . $post_id->get_error_message();
}

In this example, we update the post with ID 123 and set a new title, content, and status. We also pass true as the second argument, which indicates that we want to run the wp_kses_post() function on the post content to ensure it only contains allowed HTML tags. Finally, we check if the update was successful using the is_wp_error() function and output a success or error message accordingly.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.