-1

So I am attempting to have a ACF set the date published of a Custom Post Type... and it sort of works.

It will set the date of the post correctly the first time, but upon updates it will update the post, but also will make a duplication of the post with its date is set to Jan 01, 1970.

I can't seem to figure out the cause of the duplication, here is my code which is located in my functions.php:

add_action('save_post', 'change_content');
    global $post;
    global $wpdb;
    function change_content($post_id) {
    $datefield = get_post_meta($post_id, dateAllergy ,true);
    $post_date = date("Y-m-d H:i:s", strtotime($datefield));
    $my_post = array();
    $my_post['ID'] = $post_id;
    $my_post['post_date'] = $post_date;

if ( ! wp_is_post_revision( $post_id ) ){

        // unhook this function so it doesn't loop infinitely
        remove_action('save_post', 'change_content');

        // update the post, which calls save_post again
        wp_update_post( $my_post );

        // re-hook this function
        add_action('save_post', 'change_content');
    }   

}

Any help would be much appreciated!

Thanks in advanced!

*Edit

Solved it. Wrote a different approach, I'll leave it here incase anyone else needs something like it.

<?php

function allergy_update( $value, $post_id) {

        $new_date = date("Y-m-d H:i:s", strtotime($value));


    // update post
    $allergy_postdata = array(
        'ID'          => $post_id,
        'post_date'   => $new_date,
    );  

        if( ! ( wp_is_post_revision( $post_id) && wp_is_post_autosave( $post_id ) ) ) {

        // unhook this function so it doesn't loop infinitely
        remove_action('save_post', 'allergy_update');

        // update the post, which calls save_post again
        wp_update_post( $allergy_postdata );

        // re-hook this function
        add_action('save_post', 'allergy_update');

    }   

    return $value;
}
add_filter('acf/update_value/name=dateAllergy', 'allergy_update', 10, 3);
?>
0

Drew, one thing about your code above is that the word dateAllergy should be in quotation marks like. I'm not sure of that is the problem but it's worth changing.

 $datefield = get_post_meta($post_id, 'dateAllergy' ,true);

Also, I just noticed that your $post_id variable will be empty too. You should change that to $post->ID. That would explain why duplicate posts are being created because it the value is null or empty, Wordpress will create a separate post

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.