I’m saving my CPT in private status. So the transition would be from pending to private. Thing is, when the post was first submitted and is pending there’s a date of that submission on the post_date field in db. But when the post got published, the date updated with the current date.

I want to keep the original date of the submission of the post even the post privately published later.

So I did something like below:

function mycpt_keep_pending_date_on_publishing( $new_status, $old_status, $post ) {
    if( 'mycpt' === $post->post_type && 'pending' === $old_status && 'private' === $new_status ) :
        $pending_datetime = get_post_field( 'post_date', $post->ID, 'raw' );

        // Update the post  
        $modified_post = array(  
            'ID'            => $post->ID,  
            'post_date'     => $pending_datetime,
            'post_date_gmt' => get_gmt_from_date( $pending_datetime )
        );  

        // Update the post into the database  
        wp_update_post( $modified_post );

    endif;
}

add_action( 'transition_post_status', 'mycpt_keep_pending_date_on_publishing' );

But it’s not working. What can be the reason?

2 Answers
2

@Howdy_McGee is on the right track in his comment: by the time transition_post_status is fired, the post has already been updated (i.e., written to the db).

What you need to do is hook into wp_insert_post_data, instead of transition_post_status, as follows:

add_filter ('wp_insert_post_data', 'mycpt_keep_pending_date_on_publishing', 10, 2) ;

function
mycpt_keep_pending_date_on_publishing ($data, $postarr)
{
    if ($data['post_type'] != 'mycpt') {
        return ($data) ;
        }

    // this check amounts to the same thing as transition_post_status(private, pending)
    if ('private' != $data['post_status'] || 'pending' != $postarr['original_post_status']) {
        return ($data) ;
        }

    $pending_datetime = get_post_field ('post_date', $data['ID'], 'raw') ;

    $data['post_date'] = $pending_datetime ;
    $data['post_date_gmt'] = get_gmt_from_date ($pending_datetime) ;

    return ($data) ;
}

Note: I used the same function name as you did, but the body of that function is different.

Leave a Reply

Your email address will not be published. Required fields are marked *