0

How can I set and update the the_date according to a custom field of the post?

I have a custom field "date-time" with the following format yyyy-mm-dd hh:mm

e.g. 2015-09-30 08:12

I'd like this date to over-ride the normal date and time of the post, both on publish and when updated.

1 Answer 1

0

Normally you would write a function that gets called by the save_post hook, and use wp_update_post to update the post. The problem is, when you call wp_update_post it calls save_post, which will cause an infinite loop.

To get around that, we will unhook our function before calling wp_update_post, then re-hook it afterward.

I have not tried this, but it should work:

function change_post_date( $post_id, $post ) {

    // WordPress calls "save_post" when a post is saved, updated, autosaved,
    // revision created, or ajax called. We only want to execute this function
    // during post save and update. The next 3 "if" statements check to see why
    // save_post was called...

    // Autosave? Do nothing
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return;
    // AJAX? Do nothing
    if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
        return;
    // Post revision? Do nothing
    if ( false !== wp_is_post_revision( $post_id ) )
        return;

    // Make sure the person editing the post has permission to do so
    if ( ! current_user_can( 'edit_post', $post_id ) )
        return;

    // Get the "date-time" field
    $date_time_field = get_post_meta($post_id, 'date-time', true);

    // Unhook
    remove_action('save_post', 'change_post_date', 10);

    $args = array (
        'ID' => $post_id,
        'post_date' => $date_time_field,
        'post_date_gmt' => gmdate('Y-m-d H:i', $date_time_field )
    );

    wp_update_post( $args );

    // Re-hook
    add_action('save_post', 'change_post_date', 10);

}
add_filter('save_post', 'change_post_date', 10, 2);
8
  • Works perfectly, thanks heaps. I've looked everywhere for this. Hopefully this will help others
    – Pete
    Commented Sep 23, 2015 at 16:57
  • You're welcome; I'm glad it helped!
    – Nate Allen
    Commented Sep 23, 2015 at 17:01
  • And very well outlayed and commented
    – Pete
    Commented Sep 23, 2015 at 17:03
  • Whoops, sorry. It doesn't work .
    – Pete
    Commented Sep 23, 2015 at 17:19
  • I updated the code. Try again? And are you getting a specific error? (You may need to enable WP_DEBUG)
    – Nate Allen
    Commented Sep 23, 2015 at 17:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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