I have an option page with 2 fields.
A number field for the time interval:
booking_settings_openings_hours_interval
And a repeater field with 2 subfields:
booking_settings_opening_hours_start
booking_settings_opening_hours_end
The code below creates a list of all times (with interval X) from START to END time to populate a select field. The interval code works great but it doesn’t populate the select field with these time options.
But when I replace:
// explode the value so that each line is a new array piece
$choices = explode("\n", $choices);
With this:
// explode the value so that each line is a new array piece
echo explode("\n", $choices);
it does populate the select field but that’s not the way how to do it right..?
function yl_load_booking_time_field_choices( $field ) {
// reset choices
$field['choices'] = array();
$minutes = get_field('booking_settings_openings_hours_interval', 'booking_settings');
// get the value from options page without any formatting
if( have_rows('booking_settings_opening_hours', 'booking_settings') ) :
while ( have_rows('booking_settings_opening_hours', 'booking_settings') ) : the_row();
$start = get_sub_field('booking_settings_opening_hours_start', 'booking_settings');
$end = get_sub_field('booking_settings_opening_hours_end', 'booking_settings');
$startDate = DateTime::createFromFormat('H:i', $start);
$endDate = DateTime::createFromFormat('H:i', $end);
$interval = new DateInterval('PT'.$minutes.'M');
$dateRange = new DatePeriod($startDate, $interval, $endDate);
$choices = array();
foreach ($dateRange as $date) {
$dates = $date->format('H:i');
$choices[] = $dates;
}
// explode the value so that each line is a new array piece
$choices = explode("\n", $choices);
// remove any unwanted white space
$choices = array_map('trim', $choices);
// loop through array and add to field 'choices'
if( is_array($choices) ) {
foreach( $choices as $choice ) {
$field['choices'][ $choice ] = $choice;
}
}
endwhile;
endif;
// return the field
return $field;
}
add_filter('acf/load_field/name=booking_time', 'yl_load_booking_time_field_choices');