115 lines
2.8 KiB
PHP
115 lines
2.8 KiB
PHP
<?php
|
|
|
|
function if_needed_place_postcode_form($uri)
|
|
{
|
|
if (strpos($uri, "/shop") !== false || strpos($uri, "/winkel") !== false) {
|
|
render_dialog_html();
|
|
add_action("wp_enqueue_scripts", "dialog_styles");
|
|
add_action("wp_footer", "send_postcode_data");
|
|
if (!has_postcode()) {
|
|
add_action("wp_footer", "show_modal");
|
|
}
|
|
}
|
|
}
|
|
|
|
function dialog_styles()
|
|
{
|
|
wp_enqueue_style(
|
|
"prijs-per-postcode",
|
|
plugins_url("/assets/postcode_dialog.css", __FILE__),
|
|
);
|
|
}
|
|
|
|
function show_modal()
|
|
{
|
|
?>
|
|
<script>
|
|
const postcodeModal = document.querySelector("#postcode_modal");
|
|
postcodeModal.showModal();
|
|
</script>
|
|
<?php
|
|
}
|
|
|
|
function send_postcode_data()
|
|
{
|
|
?>
|
|
<script>
|
|
const submitBtn = document.querySelector("#postcode_modal_form");
|
|
submitBtn.addEventListener('submit', (e) => {
|
|
e.preventDefault();
|
|
const formData = new FormData(e.target);
|
|
const data = Object.fromEntries(formData.entries());
|
|
const json = JSON.stringify(data);
|
|
|
|
fetch('<? echo get_rest_url(null, "postcode-modal/v1/submit"); ?>', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-WP-Nonce': '<? echo wp_create_nonce("wp_rest"); ?>'
|
|
},
|
|
body: json
|
|
});
|
|
});
|
|
</script>
|
|
<?php
|
|
}
|
|
|
|
function render_dialog_html()
|
|
{
|
|
?>
|
|
<dialog id="postcode_modal" class="postcode_modal">
|
|
<form id="postcode_modal_form" method="post" action="">
|
|
<input type="text" name="postcode"
|
|
title="Voer een geldige Nederlandse postcode in (bijv. 1234AB of 1234 AB)."
|
|
pattern="[1-9][0-9]{3} ?(?!sa|sd|ss)[a-zA-Z]{2}"
|
|
/>
|
|
|
|
<input type="text" name="huisnummer"
|
|
pattern="\d+([-\s]?[a-zA-Z]+)?"
|
|
title="Voer een geldig huisnummer in (bijv. 1, 1A, 1-A, 1a)."
|
|
/>
|
|
<button id="postcode_modal_submit" type="submit">verzend</button>
|
|
<form>
|
|
</dialog>
|
|
<?php
|
|
}
|
|
|
|
function has_postcode()
|
|
{
|
|
if (isset($_SESSION["postcode"])) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function handle_postcode_modal($data)
|
|
{
|
|
$headers = $data->get_headers();
|
|
$params = $data->get_params();
|
|
$nonce = $headers["X-WP-Nonce"];
|
|
|
|
if (!wp_verify_nonce($nonce, "wp_rest")) {
|
|
$resp = [
|
|
"status" => "succes",
|
|
"message" => $nonce,
|
|
];
|
|
echo json_encode($resp);
|
|
exit();
|
|
}
|
|
|
|
$resp = [
|
|
"status" => "error",
|
|
"message" => "nonce do",
|
|
];
|
|
echo json_encode($resp);
|
|
exit();
|
|
}
|
|
|
|
function register_modal_api()
|
|
{
|
|
register_rest_route("postcode-modal/v1", "submit", [
|
|
"methods" => "POST",
|
|
"callback" => "handle_postcode_modal",
|
|
]);
|
|
}
|