Make WordPress Core

Opened 6 years ago

Closed 2 months ago

#48580 closed defect (bug) (invalid)

Update status in save_post hooks always true in WordPress 5.0

Reported by: oxibug's profile oxibug Owned by:
Milestone: Priority: normal
Severity: normal Version: 5.2.4
Component: Posts, Post Types Keywords:
Focuses: Cc:

Description

I think this issue shown after integration of Gutenberg editor, The {save_post} and {save_POST_TYPE} hooks always triggers {$update} as TRUE.

I made some tests, The {$update} is TRUE on saving the post for the first time and on updating also, it's always true.

<?php
add_action( 'save_post', array( $this, 'cpt_metas_save' ), 10, 3 );

public function cpt_metas_save( $post_ID, $post, $update ) {        
    $db_values = array(
        'is_new'    => 'No'
    );

    if( $update ) {
        /* Saving New Post trigger this -- always {Yes} */
        $db_values['is_new'] = 'Yes';
    }
    else {
        $db_values['is_new'] = 'No';
    }

    /* Connect to IBM Server */
    
    /* Update DB */
    update_post_meta( $post_ID, 'postmetas_save_test', wp_unslash( $db_values ) );
}

Change History (1)

#1 @SirLouen
2 months ago

  • Milestone Awaiting Review deleted
  • Resolution set to invalid
  • Status changed from new to closed

This is only meant if you use wp_insert_post directly. If you use any of the two editors, by default WP creates a draft post as soon as you start creating the post, way before you save it. This is to help with the heartbeat process and the auto-saving process. It doesn't have anything to do with Gutenberg specifically (although Gutenberg also benefits from this, as GB mostly communicates changes via WP API).

If you have to have control over this, you must add posts with wp_insert_post passing an array as the first parameter without an ID. The first time you call it, $update will be false, and it by the end, it will assign the ID and add the post to the database.

So, is $update useless? From the editor, pretty much yes. If you want to know if it's truly a new, there is a hook called draft_to_publish (its status_to_status, but in this case, the transition from draft to publish is what you are specifically looking). Also, you can hook to transition_post_status and check if the new_status is publish and the old_status is not publish. Options there are plenty, but the $update one is not meant for what you thought.

Note: See TracTickets for help on using tickets.