1

I let users add posts in draft status. After I check and see that everything is ok, I publish them. I noticed that drafts created two days ago change date after being published. Is there any way of keeping that original date?

1
  • Why did you accept such an answer? answers should have some characteristics to be accepted. Don't forget this should be the answer to your question, not a simple hint
    – Pmpr
    Dec 28 '18 at 18:27
0

you need to manually set the publish date.

2
  • Is that it? Any explanations? What do you mean by this answer? Please add some description and probably code snippets if possible
    – Pmpr
    Dec 28 '18 at 18:26
  • yes, that's it. he's describing the default WordPress functionality (i.e. setting the publish date when it's actually published). There is no one true "draft" date (that I'm aware), so there isn't a clear way to programmatically determine that date.
    – Norcross
    Dec 28 '18 at 22:05
2

The code below probably needs some adjusting, but the trick here is to obtain the date of the first revision and apply it to the post being published:

add_action(  'transition_post_status',  function ( $new_status, $old_status, $post )
{
  if ( $old_status == 'pending'  &&  $new_status == 'publish' 
       && $post->post_date_gmt == $post->post_modified_gmt) {
    $revisions = wp_get_post_revisions($post->ID);
    $oldest = NULL;
    foreach($revisions as $revision){
      $oldest = $revision->ID;
    };
    $previousdate = get_the_date( 'Y-m-d H:i:s', $oldest );
    wp_update_post(
      array (
        'ID'            => $post->ID,
        'post_date'     => $previousdate,
        'post_date_gmt' => get_gmt_from_date( $previousdate )
      )
    );
  }

}, 10, 3 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.