Quantcast
Channel: BIOSTALL » PHP
Viewing all articles
Browse latest Browse all 57

Update Published Date When Going From Draft to Published in WordPress

$
0
0

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' );

Viewing all articles
Browse latest Browse all 57

Trending Articles