محاسبه تعداد روزهای بین دو تاریخ در وردپرس
آیا تا به حال به محاسبه تعداد روزها بین دو فیلد تاریخ نیاز پیدا دارید؟ همراه باشید تا این مورد را بررسی کنیم.
نیاز به فرمی بری ثبت نام کاربران در یک رویداد چند روزه داریم. کاربر می تواند تاریخ اول (ورود) و تاریخ دوم (خروج یا پایان)را که میخواهد در رویداد شرکت کند را انتخاب کند . برای هر روز حضور، آنها باید هزینه حضور 50 هزار تومان را پرداخت کنند. چگونه میتوانیم کل قیمت را که باید برای ثبت نام پرداخت کند محاسبه کنیم؟
این قطعه به شما اجازه می دهد که تعداد روزهای بین دو فیلد تاریخ را محاسبه کنید و سپس تعداد محاسبه شده را به فیلد دیگری وارد کنید.
روش استفاده از کد :
1- کد های زیر را در فایل فانکشن تم خود کپی کنید .
2- در گرویتی فرم ، فرمی بسازید و دو تاریخ به آن اضافه کنید و همچنین یک باکس عددی جهت خروجی تفاضل تاریخ
3-قسمت آخر کد را دقت کنید و اعداد را بر اساس آیدی فرم ساخته شده ، آیدی تاریخ اول ،آیدی تاریخ دوم و آیدی باکس عددیی که اختلاف روزها را نشان میدهد تغییر دهید .
4- دقت کنید برای محاسبه مبلغ روزها فیلد دیگری به فرم اضافه کنید و در قسمت محاسبات فیلد ، فیلد روزها را ضربدر قیمت هر روز کنید.
موفق و پیروز باشید.
class GWDayCount { private static $script_output; function __construct( $args ) { extract( wp_parse_args( $args, array( 'form_id' => false, 'start_field_id' => false, 'end_field_id' => false, 'count_field_id' => false, 'include_end_date' => true, ) ) ); $this->form_id = $form_id; $this->start_field_id = $start_field_id; $this->end_field_id = $end_field_id; $this->count_field_id = $count_field_id; $this->count_adjust = $include_end_date ? 1 : 0; add_filter( "gform_pre_render_{$form_id}", array( &$this, 'load_form_script') ); add_action( "gform_pre_submission_{$form_id}", array( &$this, 'override_submitted_value') ); } function load_form_script( $form ) { // workaround to make this work for < 1.7 $this->form = $form; add_filter( 'gform_init_scripts_footer', array( &$this, 'add_init_script' ) ); if( self::$script_output ) return $form; ?> <script type="text/javascript"> (function($){ window.gwdc = function( options ) { this.options = options; this.startDateInput = $( '#input_' + this.options.formId + '_' + this.options.startFieldId ); this.endDateInput = $( '#input_' + this.options.formId + '_' + this.options.endFieldId ); this.countInput = $( '#input_' + this.options.formId + '_' + this.options.countFieldId ); this.init = function() { var gwdc = this; // add data for "format" for parsing date gwdc.startDateInput.data( 'format', this.options.startDateFormat ); gwdc.endDateInput.data( 'format', this.options.endDateFormat ); gwdc.populateDayCount(); gwdc.startDateInput.change( function() { gwdc.populateDayCount(); } ); gwdc.endDateInput.change( function() { gwdc.populateDayCount(); } ); $( '#ui-datepicker-div' ).hide(); } this.getDayCount = function() { var startDate = this.parseDate( this.startDateInput.val(), this.startDateInput.data('format') ) var endDate = this.parseDate( this.endDateInput.val(), this.endDateInput.data('format') ); var dayCount = 0; if( !this.isValidDate( startDate ) || !this.isValidDate( endDate ) ) return ''; if( startDate > endDate ) { return 0; } else { var diff = endDate - startDate; dayCount = diff / ( 60 * 60 * 24 * 1000 ); // secs * mins * hours * milliseconds dayCount = Math.round( dayCount ) + this.options.countAdjust; return dayCount; } } this.parseDate = function( value, format ) { if( !value ) return false; format = format.split('_'); var dateFormat = format[0]; var separators = { slash: '/', dash: '-', dot: '.' }; var separator = format.length > 1 ? separators[format[1]] : separators.slash; var dateArr = value.split(separator); switch( dateFormat ) { case 'mdy': return new Date( dateArr[2], dateArr[0] - 1, dateArr[1] ); case 'dmy': return new Date( dateArr[2], dateArr[1] - 1, dateArr[0] ); case 'ymd': return new Date( dateArr[0], dateArr[1] - 1, dateArr[2] ); } return false; } this.populateDayCount = function() { this.countInput.val( this.getDayCount() ).change(); } this.isValidDate = function( date ) { return !isNaN( Date.parse( date ) ); } this.init(); } })(jQuery); </script> <?php self::$script_output = true; return $form; } function add_init_script( $return ) { $start_field_format = false; $end_field_format = false; foreach( $this->form['fields'] as &$field ) { if( $field['id'] == $this->start_field_id ) $start_field_format = $field['dateFormat'] ? $field['dateFormat'] : 'mdy'; if( $field['id'] == $this->end_field_id ) $end_field_format = $field['dateFormat'] ? $field['dateFormat'] : 'mdy'; } $script = "new gwdc({ formId: {$this->form['id']}, startFieldId: {$this->start_field_id}, startDateFormat: '$start_field_format', endFieldId: {$this->end_field_id}, endDateFormat: '$end_field_format', countFieldId: {$this->count_field_id}, countAdjust: {$this->count_adjust} });"; $slug = implode( '_', array( 'gw_display_count', $this->start_field_id, $this->end_field_id, $this->count_field_id ) ); GFFormDisplay::add_init_script( $this->form['id'], $slug, GFFormDisplay::ON_PAGE_RENDER, $script ); // remove filter so init script is not output on subsequent forms remove_filter( 'gform_init_scripts_footer', array( &$this, 'add_init_script' ) ); return $return; } function override_submitted_value( $form ) { $start_date = false; $end_date = false; foreach( $form['fields'] as &$field ) { if( $field['id'] == $this->start_field_id ) $start_date = self::parse_field_date( $field ); if( $field['id'] == $this->end_field_id ) $end_date = self::parse_field_date( $field ); } if( $start_date > $end_date ) { $day_count = 0; } else { $diff = $end_date - $start_date; $day_count = $diff / ( 60 * 60 * 24 ); // secs * mins * hours $day_count = round( $day_count ) + $this->count_adjust; } $_POST["input_{$this->count_field_id}"] = $day_count; } static function parse_field_date( $field ) { $date_value = rgpost("input_{$field['id']}"); $date_format = empty( $field['dateFormat'] ) ? 'mdy' : esc_attr( $field['dateFormat'] ); $date_info = GFCommon::parse_date( $date_value, $date_format ); if( empty( $date_info ) ) return false; return strtotime( "{$date_info['year']}-{$date_info['month']}-{$date_info['day']}" ); } } # Configuration new GWDayCount( array( 'form_id' => 16, 'start_field_id' => 1, 'end_field_id' => 2, 'count_field_id' => 4 ) );
Calculate Number of Days Between Two Dates
Have you ever needed to calculate the number of days between two given date fields? Here’s a scenario for consideration.
Let’s say you have a Gravity Form set up to register users for a multi-day event. The user is able to select a start date and end date that they will be attending the event. For each day of attendance they must pay an attendance fee of $10. How can we calculate the total price they should pay for registration?
This snippet will allow to calculate the number of days between two date fields and then populate the calculated number of days into another field. This is beneficial because with this calculated number of days now available as a field value, we can use Gravity Forms’ Calculation Product to correctly calculate the registration fee based on the selected dates.
How do I install this snippet?
Easy peasy. Just copy and paste the code above into your theme’s functions.php file.
How do I use this functionality?
To use this snippet’s functionality just go directly below the snippet and instantiate the GWDayCount()
class. Instantiate is a big word but all it means is that you’ll be creating a new “instance” of the GWDayCount()
class with a set of parameters (aka options) for that specific instance.
new GWDayCount( array( |
‘form_id‘ => 9, |
‘start_field_id‘ => 1, |
‘end_field_id‘ => 2, |
‘count_field_id‘ => 3 |
) ); |
Count “Nights” Only
End date is not included in the day count so you are essentially counting the number of “nights” between the two dates.
new GWDayCount( array( |
‘form_id‘ => 9, |
‘start_field_id‘ => 1, |
‘end_field_id‘ => 2, |
‘count_field_id‘ => 3, |
‘include_end_date‘ => false |
) ); |
Once you instantiated the class you are finished! If you would like to have this functionality on multiple forms then just create a new instance of the class and fill in the parameters for the new form. That’s it!
Parameter Details
form_id
: The form ID of the form you would like to apply this functionality to.start_field_id
: The ID of the date field that will contain the start date. This field must be a date field and the parameter only holds a single field.end_field_id
: This parameter holds the ID of the date field that will contain the forms end date. This field, like the start_field_id field, must be a date field and only holds a single field ID.count_field_id
: This parameter holds the ID of the field that will be populated with the calculated number of days between the start date and end date.include_end_date
: Defaults to true. Set to this false if you would like to count only “nights” where the start date would be the check-in date and the end date would be the check-out date.
Points of Note
- This is currently only setup to work with “Date Picker” date fields. Let me know if you need this with other types of date fields in the comments.
مطلب در تاریخ 13 تیر 1400 به روز شده است
دیدگاه خود را ثبت کنید
تمایل دارید در گفتگوها شرکت کنید ؟در گفتگو ها شرکت کنید!