No value for post_date_gmt and post_modified_gmt when creating drafts in WordPress

Sand clock sitting on a bed of pebbles.
This is putting me to sleep.

I have a custom post type containing records that get dynamically updated every 24 hours from an external source. All those posts are initially created as a draft and only published to the site once their content has been confirmed, if at all.

Since I use the GMT timezone for all internally-facing timestamps and dates, I compare whether a record needs to be updated using WordPress’ GMT version of the post date.

I noticed that after a draft gets created in WordPress, the post_date and post_modified fields are properly set to the time the creation occurred, as they should, however the GMT fields for those dates, post_date_gmt and post_modified_gmt, remained at their default of 0000-00-00 00:00:00.

I did a bit of digging and found the culprit in wp-includes/post.php:

if (empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt) {
  if (!in_array( $post_status, array( 'draft', 'pending', 'auto-draft'))) {
    $post_date_gmt = get_gmt_from_date($post_date);
  } else {
    $post_date_gmt = '0000-00-00 00:00:00';

According to the code snippet above, it look like this was intentional.

Personally, I think that if you have two columns in your database, one for representing local time and one for GMT time, both should always be set and updated together for consistency. Besides their offset, I believe the intent is for them to be identical, so why not enforce that from the start?

Either way, the solution to this was to ensure that I manually set the GMT time for all drafts during the insert. I calculated the GMT time using the get_gmt_from_date function, which is the same function WordPress uses when it needs to convert local time to GMT:

$post = array();
$post['post_date'] = current_time('mysql');
$post['post_date_gmt'] = get_gmt_from_date($post['post_date']);
$post['post_status'] = 'draft';

In the end, while the reason for not setting the GMT time for drafts remains a mystery, at least it was pretty straightforward to solve.

Featured image by Aron Visuals.

Comments (1)

Previously posted in WordPress and transferred to Ghost.

June 11, 2015 at 1:22 pm

Dude… U nailed it.
Respect ++