Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ACF Date Time Picker – set end date to after start date - With two related Date Time Picker fields limit the end date to be after the start date. https://www.damiencarbery.com/2021/10/acf-date-time-picker-set-end-date-to-after-start-date/
<?php
/*
Plugin Name: ACF Date Time Picker - set end date to after start date
Plugin URI: https://www.damiencarbery.com/2021/10/acf-date-time-picker-set-end-date-to-after-start-date/
Description: With two related Date Time Picker fields limit the end date to be after the start date.
Author: Damien Carbery
Version: 0.2
*/
// Add the JavaScript block only if one of the two Date Time Picker fields is being displayed.
function dcwd_setup_datetimepicker_init( $field ) {
// If the field has class or 'start-dp-wrapper' or 'end-dp-wrapper'
// then include the pairing JavaScript.
if ( is_array( $field['wrapper'] ) &&
(('start-dtp-wrapper' == $field['wrapper']['class'] ) ||
('end-dtp-wrapper' == $field['wrapper']['class'] ) ) ) {
add_action('acf/input/admin_footer', 'dcwd_init_datetimepicker' );
}
}
// Only run for Date Time Picker fields.
add_action( 'acf/render_field/type=date_time_picker', 'dcwd_setup_datetimepicker_init' );
// JavaScript code to initialise and change UX of date picker fields.
function dcwd_init_datetimepicker() {
?>
<script>
// This filter allows the date picker settings to be customized for each date picker field.
// Called before the date picker instance is created.
// See: https://trentrichardson.com/examples/timepicker/ (and https://api.jqueryui.com/datepicker/)
acf.add_filter('date_time_picker_args', function( args, field ){
if ( field.hasClass('start-dtp-wrapper') || field.hasClass('end-dtp-wrapper') ) {
args.minDate = -2; // Minimum selectable date is two days ago.
//args.yearRange = '-0:+10'; // Limit to this year to +10 years.
}
return args;
});
</script>
<script>
jQuery.noConflict();
jQuery(document).ready( function($){
// Ensure end date is not earlier than start date.
$(document).on("change", ".start-dtp-wrapper .hasDatepicker", function( e ) {
var start_date = $(this).val();
//var start_date = $(this).datetimepicker( 'getDate' );
var end_date_time_picker = $(this).parents('.acf-field').next().find('.hasDatepicker');
//var end_date = end_date_time_picker.datetimepicker( 'getDate' );
var end_date = end_date_time_picker.val();
// This block copied from Event Manager (events-manager/includes/js/events-manager.js)
// If start date changed to be after end date then set the end date to start date.
if ( end_date != '' && start_date > end_date ) {
end_date_time_picker.datetimepicker( "setDate" , start_date );
}
// Send minimum selectable end date to the start date. Note that the minimum time is not set.
end_date_time_picker.datetimepicker( "option", 'minDate', start_date );
});
});
</script>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment