Skip Navigation

[Resolved] Set CPT Date to today by default

This support ticket is created 6 years, 5 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 3 replies, has 2 voices.

Last updated by Christian Cox 6 years, 5 months ago.

Assisted by: Christian Cox.

Author
Posts
#1104561
2018-09-10_15-53-55.png
2018-09-10_15-53-21.png

Tell us what you are trying to do?
Hello, I've created a field group and added it to standard WP-posts.
How can I set date field value for today while creating/editing post in WP-Admin. Please see screenshots attached//

Thank you1

What is the link to your site? hidden link

#1104771

Hi, you can add this custom code to your child theme's functions.php file. This will automatically set the custom field date whenever a Post is created or edited:

add_action( 'save_post', 'set_sht_date_field_to_today', 100, 3 );
function set_sht_date_field_to_today( $post_id, $post, $update ) {
  if ( $post->post_type == 'post' ) {
    update_post_meta( $post_id, 'wpcf-sht-event-date_from-new', date('U') );
  }
}

This will overwrite any date that already exists in the date field, and change it to today's date.

#1105298

Dear Christian, is it possible to add if field empty condition... I mean, no need to overwrite in case not empty...

Thanks!

#1105524

Sure, try this variation:

add_action( 'save_post', 'set_sht_date_field_to_today', 100, 3 );
function set_sht_date_field_to_today( $post_id, $post, $update ) {
  if ( $post->post_type == 'post' ) {
    $date = get_post_meta( $post_id, 'wpcf-sht-event-date_from-new', true);
    if( $date ) { 
      return;
    }
    update_post_meta( $post_id, 'wpcf-sht-event-date_from-new', date('U') );
  }
}