Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Giannisduke/485967b78d9121c085a1d493670e076d to your computer and use it in GitHub Desktop.
Save Giannisduke/485967b78d9121c085a1d493670e076d to your computer and use it in GitHub Desktop.
This snippet for the wordpress facetwp plugin is used to group the two facets (start and end) generated by the date_range facet when "Fields to show" is set to "Start + End Dates".
<?php
add_action( 'wp_footer', 'facetwp_date_range_in_single_calendar',100);
function facetwp_date_range_in_single_calendar() {
?>
<script>
(function($) {
if ( 'undefined' !== typeof FWP ) {
FWP.hooks.addFilter('facetwp/set_options/date_range', function(flatpickr_opts, extras) {
var parent = $(extras.element).closest('.facetwp-type-date_range');
// We're in a "Start + End Dates" situation.
if ( parent.find('.facetwp-date').length > 1 ){
// Dates prior to today are disabled.
flatpickr_opts['minDate'] = "today";
flatpickr_opts['mode'] = "range";
flatpickr_opts['onChange'] = function(dateObj, dateStr, instance){
// When the start_date and end_date are filled in
if (dateObj.length>1) {
if ( $(instance.element).closest('.facetwp-type-date_range').length > 0 ){
parent.find('.facetwp-date-min').attr('value',flatpickr.formatDate(dateObj[0], 'Y-m-d'));
parent.find('.facetwp-date-max').attr('value',flatpickr.formatDate(dateObj[1], 'Y-m-d'));
// We launch the ajax search if we haven't disabled the auto refresh.
if( FWP.auto_refresh ){
FWP.autoload();
}
}
}
};
flatpickr_opts['onReady'] = function(dateObj, dateStr, instance){
if ( $(instance.element).hasClass('facetwp-date-max') ){
// We modify the behavior of the end_date facet
instance.destroy();
$(instance.element).attr({
'type':'hidden',
'readonly':'readonly'
});
$(instance.element).closest('.facetwp-type-date_range').addClass('date_range_min_and_max');
}else{
var datefin = parent.find('.facetwp-date-max').attr('value');
if ( datefin != '' ){
datefin = flatpickr.parseDate(datefin, "Y-m-d");
dateObj.push(datefin);
instance.setDate(dateObj);
}
// Normal behaviour
var clearBtn = '<div class="flatpickr-clear">' + FWP_JSON.datepicker.clearText + '</div>';
$(clearBtn).on('click', function() {
instance.clear();
// Clear end_date field
parent.find('.facetwp-date-max').attr('value','');
instance.close();
if( FWP.auto_refresh ){
FWP.autoload();
}
})
.appendTo($(instance.calendarContainer));
}
};
}
return flatpickr_opts;
});
}
})(jQuery);
</script>
<?php
}
// This part of the CSS can be used to complete the above code.
/*
.facet .facetwp-type-date_range.date_range_min_and_max .flatpickr-alt{
width:100%;
}
.facet .facetwp-type-date_range.date_range_min_and_max::before{
display:none;
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment