How to Use wp_update_post to Update WordPress Posts

Download all in one WordPress cheat sheet

Updating posts via the WordPress dashboard is a simple and easy task.

However, you can also test out more advanced WordPress features or learn how WordPress functions work during the process. To accomplish this, consider updating posts with the wp_update_post() function.

In this tutorial, we will explain the WordPress wp_update_post() function and cover its most popular use cases.

Parameters of the wp_update_post WordPress Function

The wp_update_post() function updates existing posts in the database. Check out its parameters below:

wp_update_post( $postarr, $wp_error, $fire_after_hooks );
  • $postarr – the post data array.
  • $wp_error – determines whether to return a WP_Error class in case of an error. Set as false by default.
  • $fire_after_hooks – decides whether to fire the after-insert hooks. By default, it is set as true.

As for return values, the function will return the post ID if successful. Otherwise, you will see WP_Error or value zero.

In other words, wp_update_post() takes an array of post data as an argument and updates the corresponding posts in the database with the new post data.

Check the function source from the wp-includes/post.php file below:

function wp_update_post( $postarr = array(), $wp_error = false, $fire_after_hooks = true ) {

function wp_update_post( $postarr = array(), $wp_error = false, $fire_after_hooks = true ) {
	if ( is_object( $postarr ) ) {
		// Non-escaped post was passed.
		$postarr = get_object_vars( $postarr );
		$postarr = wp_slash( $postarr );
	}

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

	if ( is_null( $post ) ) {
		if ( $wp_error ) {
			return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
		}
		return 0;
	}

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

	// Passed post category list overwrites existing category list if not empty.
	if ( isset( $postarr['post_category'] ) && is_array( $postarr['post_category'] )
		&& count( $postarr['post_category'] ) > 0
	) {
		$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' ), true )
		&& 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 ( 'attachment' === $postarr['post_type'] ) {
		return wp_insert_attachment( $postarr, false, 0, $wp_error );
	}

	// Discard 'tags_input' parameter if it's the same as existing post tags.
	if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $postarr['post_type'], 'post_tag' ) ) {
		$tags      = get_the_terms( $postarr['ID'], 'post_tag' );
		$tag_names = array();

		if ( $tags && ! is_wp_error( $tags ) ) {
			$tag_names = wp_list_pluck( $tags, 'name' );
		}

		if ( $postarr['tags_input'] === $tag_names ) {
			unset( $postarr['tags_input'] );
		}
	}

	return wp_insert_post( $postarr, $wp_error, $fire_after_hooks );
}

How to Use the wp_update_post Function in WordPress

To use the wp_update_post() function, you need to create a default array first, which will be passed as a parameter. Then, fill in the function with the fields you want to change, namely:

  • ID – a unique number assigned to each post.
  • post_author – a post author’s user ID.
  • post_content – post content, including text and images.
  • post_date – the date and time when the post was published.
  • post_date_gmt – the GMT time zone in which the post date is written.
  • post_excerpt – posts’ user-defined excerpt.
  • post_title – a full post title.
  • post_status – a current post status, such as published, draft, or trash.
  • comment_status – enable or disable comments for a given post.
  • post_type – a default post type, such as a page or an attachment.
  • post_modified – posts’ last modified date and time.
  • post_modified_gmt – the GMT time zone in which the post was modified.
  • ping_status – open or close a post for pingbacks.
  • post_password – a post password. It will be empty if there is no password.
  • post_parent – a parent post ID if it exists.
  • comment_count – the number of comments on a post.

Pro Tip

The wp_update_post() function can cause an infinite loop. It happens when post_type is set as revision and wp_update_post() is used within the save_post hook. To prevent this, make sure that post_type is not set as revision.

WordPress wp_update_post Function Examples

Check out a few popular use cases of the wp_update_post() function.

Update Post Meta

With wp_update_post(), you can also update your WordPress posts metadata to improve your SEO efforts. Just use the code below:

$mydata = array(
  'ID' => $post_id,
  'post_content' => $content,
  'meta_input' => array(
  'meta_key' => $meta_value,
  'next_meta_key' => $next_meta_value
   )
 );

wp_update_post( $data );

Update Post

It’s possible to update a post more easily with wp_update_post(). All you need to do is pass the post ID along with the elements you want to update. Keep in mind that element names must match those in your database.

$my_awesome_post = array(
      'ID'           => 10,
      'post_title'   => 'This is my awesome post title',
      'post_content' => 'This is my awesome updated content.',
  );

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

We recommend enabling an error display with the following code if the update doesn’t work.

<?php
wp_update_post( $current_item, true );						  
if (is_wp_error($post_id)) {
	$errors = $post_id->get_error_messages();
	foreach ($errors as $error) {
		echo $error;
	}
}
?>

Make sure to disable the error display again when publishing the changes to production.

Automatically Publish a Post In The Future

You can set a post to be published in the future. For example, the following code sample will schedule a post to be published tomorrow:

$time = strtotime( 'tomorrow' );
$my_post = array(
    'ID'            => 1,
    'post_status'   => 'future',
    'post_date'     => date( 'Y-m-d H:i:s', $time ),
    'post_date_gmt' => gmdate( 'Y-m-d H:i:s', $time ),
);
wp_update_post( $my_post );

Conclusion

Updating your posts via a function is a great way to learn more about the advanced WordPress features.

In this tutorial, we went over the wp_update_post() function, shown how it works, and provided a few helpful use cases.

We hope that now you understand the wp_update_post() function better and will be able to use it successfully with your WordPress projects.
Should you have any questions, check out our WordPress guide or leave a comment below.

Author
The author

Ignas R.

Ignas takes great satisfaction in helping people tackle even the most complex technical issues. His current goal is to write easy-to-follow articles so that these issues will not happen at all. During his free time, Ignas likes to play video games and fix up things around his house.