can’t edit post_modified in wp_insert_post (bug?)

It is not bug, actually WordPress does not allow (using arguments) to set post modification date. Internally WordPress set it to current time if you are updating an existing post else just set it to post date.

in /wp-includes/post.php#L3192 you can see wp_insert_post does not use this argument

if ( $update || '0000-00-00 00:00:00' == $post_date ) {
        $post_modified     = current_time( 'mysql' );
        $post_modified_gmt = current_time( 'mysql', 1 );
} else {
        $post_modified     = $post_date;
        $post_modified_gmt = $post_date_gmt;
}

The documentation does not seems to me correct. I’ve created a ticket#36597 for this. Hopefully documentation will be corrected.

PS: However you can use wp_insert_post_data filter to set your custom modification date.

EDIT: WordPress already running a insert query and then running another SQL query just to update post modification time is not the good idea, better we can alter the date just before WordPress insert it to database. I think it will not cost you much than a separate SQL query.

First add a filter just before wp_insert_post and remove it so will not effect other insert functions.

add_filter( 'wp_insert_post_data', 'alter_post_modification_time', 99, 2 );
$wp_id = wp_insert_post( $wp_test );
remove_filter( 'wp_insert_post_data', 'alter_post_modification_time', 99, 2 );

In callback function set the modification time to which we have passed in wp_insert_post() function arguments. (Do not forgot to add post modification time which you’ve removed from arguments)

function alter_post_modification_time( $data , $postarr ) {
    if (!empty($postarr['post_modified']) && !empty($postarr['post_modified_gmt'])) {
        $data['post_modified'] = $postarr['post_modified'];
        $data['post_modified_gmt'] = $postarr['post_modified_gmt'];
    }

    return $data;
}

Leave a Comment