0

I created a custom field using Advanced Custom Fields (but I think ACF is optional) and I want him to dynamically fill the publish post date when I publish a post.

Example :

If I publish a post today, I want when the action of publishing is done to find 30/09/2020 in my custom field If I schedule my post for tomorrow then I want to find tomorrow 01/10/2020 in my custom field.

Same idea if I publish my article at an earlier date.

I already tried this (in relation with ACF plugin but any other type of solution is find to me) :

add_action('acf/save_post', 'my_acf_save_post');
function my_acf_save_post( $post_id ) { 
    $value = get_the_date();
    update_field('name_of_my_custom_field', $value, $post_id);
}

But I always get today’s date and not the real published date.

One other thing, I don’t want my custom field to be updated when I will update my post in the future. So I thought about a condition like: IF my custom field is filled with data THEN I do nothing but I am not able to do it.

Any ideas?

Thanks in advance and sorry for my poor English.

0

When you get the date with function get_the_date() you need to pass a $post object or ID as a second parameter:

$date = get_the_date( $date_format, $post );

The first parameter here is the PHP date format. The second - Post ID or WP_Post object

Here is an example that should work:

add_action( 'acf/save_post', 'my_acf_save_post' ); 

function my_acf_save_post( $post_id ) {
    $date = get_the_date( 'Y-m-d H:i:s', $post_id );

    update_field( 'your_meta_key', $date, $post_id ); 
}

Check the documentation on get_the_date() function https://developer.wordpress.org/reference/functions/get_the_date/

5
  • Thanks for your help, I change my function like that : add_action('acf/save_post', 'my_acf_save_post'); function my_acf_save_post( $post_id ) { $date_format = get_option( 'date_format' ); $value = get_the_date($date_format, $post_id); update_field('name_of_my_custom_field', $value, $post_id); } But I still always get today's date when I try to schedule a post for example. – Jonathan Aryup Oct 2 '20 at 12:32
  • What type of ACF field do you use? Is it a regular Text field, or Date Time Picker? @JonathanAryup – geouser Oct 2 '20 at 13:00
  • For the moment it is a date type of field, but i can switch to a text field if this is easier. – Jonathan Aryup Oct 2 '20 at 13:18
  • I've added an example to the answer, it worked for me with both Text and Date Time Picker field – geouser Oct 2 '20 at 13:21
  • It works fine for me too thanks a lot ! – Jonathan Aryup Oct 2 '20 at 14:45

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.