Update Published Date When Going From Draft to Published in WordPress

April 10th, 2014 - Posted by Steve Marks to PHP, Web Development.

The published date of a page or post in WordPress is set when the article is first added to a website. This is then used in various scenarios; ordering news articles in date order, displaying when a blog post was first added, or setting the ‘pubDate’ value in an RSS feed.

An issue I came across today was that this date is only set when the post is first added to WordPress. If, at a later date, you set it’s status to ‘Draft‘ and then publish it again, the published date remains as it was.

I can definitely understand why this is and don’t claim this to be any sort of bug. However, for my particular scenario, I needed this published date to get updated to the current date and time if it went from ‘Draft’ to ‘Published’.

The Solution

Fortunately, as with most things, WordPress has a hook readily available to be used that handles any post status transitions.

The scenario I was most interested in was when a post’s status went from ‘Draft’ to ‘Published’ so I was able to use an action called ‘draft_to_publish‘. Using this I was then able to conjure up the following code:

function my_update_published_date( $post ) 
    // I only wanted this to apply for a particular post type
    if ($post->post_type == 'myposttype') 
        // Update the post
        $my_post = array(
            'ID'            => $post->ID,
            'post_date'     => date("Y-m-d H:i:s"),
            'post_date_gmt'     => date("Y-m-d H:i:s")
        // Update the post into the database
        wp_update_post( $my_post );
add_action( 'draft_to_publish', 'my_update_published_date' );
This entry was posted on Thursday, April 10th, 2014 at 10:36 am by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (1)
  1. Luppis says:

    Thank you!

    I have been looking how to do this for ages. This REALLY made my day and helped me out.