Wordpress - wp_update_post() example... how to update the_content in a textarea?

I'm getting the same problem. My code is in the single.php file. I'm using the code from this article: Front end post editing using a form

After clicking on submit, the code in single.php does run wp_update_post() with the post ID being returned. Since this is being run from a template file, the wp_query has already been populated so the page still renders with the old post data. If I refresh without submitting, the new data is populated.

I'm not sure if this is the best solution for it, but it works. After wp_update_post() is run, I overwrite the global $wp_query variable using the same query that was run before this template file was called.

global $wp_query;
if ('POST' == $_SERVER['REQUEST_METHOD'] && !empty($_POST['post_id']) && !empty($_POST['post_title']) && isset($_POST['update_post_nonce']) && isset($_POST['post_content'])) {
    $post_id = $_POST['post_id'];

    $post_type = get_post_type($post_id);
    $capability = ('page' == $post_type) ? 'edit_page' : 'edit_post';
    if (current_user_can($capability, $post_id) && wp_verify_nonce($_POST['update_post_nonce'], 'update_post_' . $post_id)) {
        $post = array(
            'ID' => esc_sql($post_id),
            'post_content' => wp_kses_post($_POST['post_content']),
            'post_title' => wp_strip_all_tags($_POST['post_title'])
        );
        $result = wp_update_post($post, true);

        if (is_wp_error($result)){
            wp_die('Post not saved');
        }
        $wp_query = new WP_Query($wp_query->query);  //resets the global query so updated post data is available.

    } else {
        wp_die("You can't do that");
    }
}

I've tried calling wp_reset_postdata() and wp_reset_query() instead but I'm guessing it is resetting to a cached copy because I still get the old post data.

Another solution that worked was getting the current url using:

global $wp;
$current_url = home_url(add_query_arg(array(),$wp->request)); 

and then after wp_update_post():

wp_redirect($current_url);

The code for the $current_url was found here.


You can override the WP_Post properties and send it to wp_update_post:

/** @var WP_Post $post */
$post = get_post( 123 );

$post->post_content = "Some other content";

wp_update_post( $post );

I find it easier than an array.