我正在尝试为WordPress建立自己的预约系统。为此,我创建了一个名为;约会;。当用户从服务列表中选择服务时,将列出可用的日期和时间。选择可用日期和时间并创建约会后,将显示一个名为;“约会\\u日期时间”;已为此约会添加。这里是问题的起点。
Two different users should not be able to make an appointment for the same service at the same time. 因此,当用户尝试创建约会时,将使用以下方法检查他选择的日期和时间是否可用。
$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
// ...
}
下面是我使用的ajax代码:
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. 我有什么办法可以防止这种情况发生吗?
SO网友:tiago calado
首先,在使用新的WP\\u查询结束时,最好始终使用WP\\u reset\\u postdata();确保没有任何东西会破坏您的数据库。
$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,
)
)
wp_reset_postdata();
));
为了回答您的问题,为什么不在数据库中设置约会之前按下按钮时使用另一个if呢。就像这样
if ( !empty($already_reserved->posts) ) {
$response = \'Sorry, this date is full.\';
} else {
// create new appointment post
// ...
// the user has everything and click the button
if ( !empty($already_reserved->posts) ) {
$response = \'Sorry, this date is no longer available.\';
} else {
// the appointment is set on the database
}
}
这是假设首先对日期进行验证,然后用户按下按钮进行确认。如果按钮具有特定功能,请尝试编辑该功能以进行此验证,然后再在数据库上设置约会。