I'm trying to make my own appointment system for WordPress. For this, I created a post type called "appointments". When users select a service from the service list, the available dates and times are listed. When the available date and time are selected and the appointment is created, a meta key named "appointment_datetime" is added for this appointment. Here is where the problem started.
Two different users should not be able to make an appointment for the same service at the same time. Therefore, when a user tries to create an appointment, the following method is used to check whether the date and time he chose are available.
$already_reserved = new WP_Query(array(
'post_type' => 'appointments',
'fields' => 'ids',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'datetime',
'value' => $date_time, // timestamps
'type' => 'numeric',
'compare' => '='
)
),
'tax_query' => array(
array(
'taxonomy' => 'services',
'field' => 'id',
'terms' => $service_id,
)
)
));
if ( !empty($already_reserved->posts) ) {
$response = 'Sorry, this date is full.';
} else {
// create new appointment post
// ...
}
And here is the ajax code I used:
var $response = jQuery('#response');
$('#createnew').click(function () {
var service = document.getElementById('service').value;
var datetime = document.getElementById('datetime').value;
$response.html("<div class='loading'>Waiting...</div>");
$.ajax({
type: 'POST',
url: myajax.ajaxurl,
data: {
action: 'new_appoitment',
service: service,
datetime: datetime,
// ... another customer details
},
success: function(data, textStatus, XMLHttpRequest) {
$response.html('');
$response.append(data);
}
});
});
After all; When two different users click the button at the same time, they can create an appointment for the same date and time. Is there any way I can prevent this?