Create CPT called “Booking” and create custom field text type, name it Booking Date (slug is booking_date). Then create form in Bricks Builder with a date picker field.
We are gonna save form submission into Booking CPT. Add “Custom” action to form.
function my_form_save_to_cpt($form)
{
$fields = $form->get_fields();
// The Bricks Form ID is the last part of the CSS ID
// So if a form has a CSS ID of bricks-element-fszxsr, then the form ID is fszxsr
$formId = $fields['formId'];
// Replace this comment with the description of the form
// Copy and paste the IF block below to add custom action for other forms
if ($formId == 'lrhbkm') {
$name = $fields['form-field-9f4940'];
$date = $fields['form-field-xeqkwh'];
$email = $fields['form-field-e6a6c3'];
$messages = $fields['form-field-f1df96'];
$new_post = array();
$new_post['ID'] = '';
$new_post['post_type'] = 'booking';
$new_post['post_status'] = 'draft';
if (isset($name) && !empty($name)) {
$new_post['post_title'] = 'Booking ' . $name . '';
} else {
$new_post['post_title'] = 'Message from user';
}
if (isset($date) && !empty($date)) {
$new_post['meta_input']['booking_date'] = $date;
} else {
$new_post['meta_input']['booking_date'] = $date;
}
if (isset($email) && !empty($email)) {
$new_post['meta_input']['email'] = $email;
} else {
$new_post['meta_input']['email'] = $email;
}
if (isset($messages)) {
$new_post['post_content'] = $messages;
} else {
$new_post['post_content'] = 'No Message was submitted';
}
wp_insert_post($new_post);
return;
}
}
add_action('bricks/form/custom_action', 'my_form_save_to_cpt', 10, 1);I use json_decode to get the result from querying booking_date from CPT so we can use it as an disable option to flatpickr js.
function get_disabled_dates_json( $post_type, $custom_field ) {
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
$disabled_dates = array();
while ( $query->have_posts() ) {
$query->the_post();
$date = get_post_meta( get_the_ID(), $custom_field, true );
if ( $date ) {
$disabled_dates[] = $date;
}
}
wp_reset_postdata();
return wp_json_encode( $disabled_dates );Load flatpickr css and js by enqueue those file and target the date picker field to initialize the flatpickr. Use code below
function initialize_flatpickr() {
$disabled_dates_json = get_disabled_dates_json( 'booking', 'booking_date' ); // booking is CPT slug and booking_date is custom field slug
wp_enqueue_script('bricks-flatpickr');
wp_enqueue_style('bricks-flatpickr');
?>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function (event) {
const myInput = document.querySelectorAll('[name="form-field-xeqkwh"]'); // change this into your actual form date field name
const fp = flatpickr(myInput, {
enableTime: false,
dateFormat: "d/m/Y",
disable: <?php echo $disabled_dates_json; ?>,
locale: {
firstDayOfWeek: 1
}
});
});
</script>
<?php
}
add_action('wp_footer', 'initialize_flatpickr');