Compare commits

...

18 Commits

Author SHA1 Message Date
Remo Zaros
ef3abb9514 clean up prijs-per-postcode 2026-07-01 11:19:33 +02:00
Remo Zaros
03f7e9857d move register_modal_api to main file 2026-07-01 11:18:44 +02:00
Remo Zaros
bdeae51bdb rewrite pppr_is_local 2026-07-01 11:17:12 +02:00
Remo Zaros
2df645be97 remove trim()s. was used twice 2026-06-30 10:46:08 +02:00
Remo Zaros
4173e32489 Change instruction text 2026-06-30 10:43:40 +02:00
Remo Zaros
a43d6213b5 Remove the PHP class 2026-06-29 18:53:19 +02:00
Remo Zaros
76ca74e1a6 clear shopping card when modal is shown 2026-06-29 13:35:30 +02:00
Remo Zaros
4f8de2e1f4 Make chechout work in Safari 2026-06-29 11:39:43 +02:00
Remo Zaros
159f96c9c2 Trim values 2026-06-29 09:42:10 +02:00
Remo Zaros
72bfb88bfb Make address fields populate dynamic. 2026-06-27 13:43:48 +02:00
Remo Zaros
0b467752fb remove 'winkel' from code 2026-06-26 18:28:41 +02:00
Remo Zaros
ab97611783 change cookie to work with cache plugin 2026-06-26 18:27:21 +02:00
Remo Zaros
8d42eee2c1 Correct reset function 2026-06-25 11:02:11 +02:00
Remo Zaros
29109c47d1 change version nr 2026-06-25 11:01:42 +02:00
Remo Zaros
297ba93508 Change sercure when http or https is used 2026-06-25 11:01:11 +02:00
Remo Zaros
d805477f4e Make sure prices show 2026-06-22 12:24:03 +02:00
Remo Zaros
e5e17cbafc swap session with cookie with hash 2026-06-22 09:34:14 +02:00
Remo Zaros
ba63181e6a Tried to set cookie 2026-06-13 18:06:26 +02:00
5 changed files with 598 additions and 301 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
wp-pppr-salt.php

View File

@@ -40,7 +40,7 @@ function generate_admin_page()
<ul> <ul>
<li>Het formaat voor een reeks is #### - #### (voorbeeld: 5000 - 5199).</li> <li>Het formaat voor een reeks is #### - #### (voorbeeld: 5000 - 5199).</li>
<li>Plaats één reeks op één regel.</li> <li>Plaats één reeks op één regel.</li>
<li>Een reeks van 1 is geldig. (voorbeeld: 5000 - 5000)</li> <li>Een reeks van 1 is geldig. (voorbeeld: 5000 - 5000).</li>
<li>Om een reeks te verwijderen. Wis de reeks en sla vervolgens de wijzigen op.</li> <li>Om een reeks te verwijderen. Wis de reeks en sla vervolgens de wijzigen op.</li>
</ul> </ul>
</div> </div>

175
pppr_cookie.php Normal file
View File

@@ -0,0 +1,175 @@
<?php
function create_pppr_salt() {
// 1. Check permissions first (Optional but recommended)
if ( ! wp_is_writable( plugin_dir_path( __FILE__ ) ) ) {
// Log error or handle failure
return false;
}
// 2. Define path INSIDE the plugin folder
$file_path = plugin_dir_path( __FILE__ ) . 'wp-pppr-salt.php';
// 3. Get the salt
$current_salt = wp_salt( 'auth' );
if ( empty( $current_salt ) ) {
return false;
}
// 4. Prepare content
$file_content = "<?php\n";
$file_content .= "// Auto-generated salt constant\n";
$file_content .= "// Exported salt from " . date( 'Y-m-d H:i:s' ) . "\n";
$file_content .= "define( 'WP_PPPR_SALT', '{$current_salt}' );\n";
// 5. Write the file
$bytes_written = file_put_contents( $file_path, $file_content, LOCK_EX );
// 6. Verify success
if ( $bytes_written === false ) {
// Handle error (e.g., log it)
return false;
}
return true;
}
function set_pppr_cookie($is_local, $street_name, $house_number, $postcode, $city) {
$data_string = (int)$is_local . "|" . $street_name . "|" . $house_number . "|" . $postcode . "|" . $city;
$signature = hash_hmac('sha256', $data_string, WP_PPPR_SALT);
$cookie_value = $data_string . "|" . $signature;
$cookie_domain = $_SERVER['SERVER_NAME'];
$is_secure = is_ssl();
setcookie("PPPR", $cookie_value, [
'expires' => time() + 7200,
'path' => '/',
'domain' => $cookie_domain,
'secure' => $is_secure,
'httponly' => true, // Prevent JavaScript access
'samesite' => 'Lax' // Protect against CSRF
]);
}
function unset_pppr_cookie( $path = '/') {
unset($_COOKIE["PPPR"]);
$domain = $_SERVER['SERVER_NAME'];
$is_secure = is_ssl();
// 3. Send the delete command with ALL matching parameters
setcookie(
"PPPR",
'',
time() - 3600,
'/',
$domain,
$is_secure, // Critical: Must match the 'secure' flag used when setting
true
);
}
function update_expire_pppr_cookie() {
if (!isset($_COOKIE['PPPR'])) {
return false;
}
$cookie_value = $_COOKIE['PPPR'];
$cookie_domain = $_SERVER['SERVER_NAME'];
$is_secure = is_ssl();
setcookie("PPPR", $cookie_value, [
'expires' => time() + 7200,
'path' => '/',
'domain' => $cookie_domain,
'secure' => $is_secure,
'httponly' => true, // Prevent JavaScript access
'samesite' => 'Lax' // Protect against CSRF
]);
}
function verify_pppr_cookie_string() {
if (!isset($_COOKIE['PPPR'])) {
return false;
}
$cookie_value = $_COOKIE['PPPR'];
$last_delimiter = strrpos($cookie_value, '|');
if ($last_delimiter === false) {
return false;
}
$data_part = substr($cookie_value, 0, $last_delimiter);
$hash_part = substr($cookie_value, $last_delimiter + 1);
// Check if salt is defined
if (!defined('WP_PPPR_SALT')) {
return false;
}
$expected_hash = hash_hmac('sha256', $data_part, WP_PPPR_SALT);
return hash_equals($expected_hash, $hash_part);
}
function get_PPPR_data() {
// 1. Check if cookie exists
if (!isset($_COOKIE['PPPR'])) {
return false;
}
$cookie_value = $_COOKIE['PPPR'];
// 2. Split safely using the LAST delimiter (handles pipes in street names)
$last_delimiter = strrpos($cookie_value, '|');
if ($last_delimiter === false) {
return false; // Malformed cookie
}
$data_part = substr($cookie_value, 0, $last_delimiter);
$provided_hash = substr($cookie_value, $last_delimiter + 1);
// 3. CRITICAL: Verify the signature before trusting ANY data
// Ensure WP_PPPR_SALT is defined and matches the setter exactly
if (!defined('WP_PPPR_SALT')) {
return false;
}
$expected_hash = hash_hmac('sha256', $data_part, WP_PPPR_SALT);
if (!hash_equals($expected_hash, $provided_hash)) {
return false; // Tampered or invalid cookie
}
// 4. Only now is it safe to explode the verified data
$fields = explode('|', $data_part);
// Ensure we have enough fields
if (count($fields) < 5) {
return false;
}
return [
'is_local' => (bool)$fields[0],
'street' => $fields[1],
'house_number' => $fields[2],
'postcode' => $fields[3],
'city' => $fields[4],
];
}
function pppr_is_local() {
// Check if the cookie exists and is not empty
if (isset($_COOKIE['PPPR']) && !empty($_COOKIE['PPPR'])) {
// Ensure it's treated as a string before accessing the first character
$cookie_value = (string) $_COOKIE['PPPR'];
$first_char = $cookie_value[0] ?? '';
return $first_char === '1';
}
// Return false if cookie is missing or empty
return false;
}

View File

@@ -1,83 +1,70 @@
<?php <?php
/*
* Plugin Name: Prijs per poscodeereeks.
* Description: Producten worden gefiltered aan de hand van opgegegeven postcodereeksen.Gebruikers met een postcode die in een opgegegeven postcodereeks valt zal een lokale prijs zien. Waar elke gebruiker met een postcode die buiten eem opgegeven reeks valt zal de reguliere prijs te zien krijgen.
* Author: Remo Zaros
* Version: 0.9.090
* Text Domeain: prijs-per-postcode
*/
require_once plugin_dir_path(__FILE__) . "session_dialog.php"; require_once plugin_dir_path(__FILE__) . "session_dialog.php";
require_once plugin_dir_path(__FILE__) . "admin.php"; require_once plugin_dir_path(__FILE__) . "admin.php";
/* require_once plugin_dir_path(__FILE__) . "pppr_cookie.php";
* Plugin Name: Prijzen per poscodeereeks.
* Description: Producten worden gefiltered aan de hand van opgegegeven postcodereksen.Klanten met een postcode Die in de opgegegeven postcode reeks vallen zullen een lokale prijs zien. Waar iedereen die niet in de reeks vallen de overige regios prijs te zien krijgt.
* Author: Remo Zaros
* Version: 0.9.6
* Text Domeain: prijs-per-postcode
*/
if (!defined("ABSPATH")) { if (!defined("ABSPATH")) {
echo "big bag of potatoes"; echo "big bag of potatoes";
exit(); exit();
} }
class PrijsPerPostcode /*
{ * Create salt
public function __construct() */
{ register_activation_hook( __FILE__, 'create_pppr_salt' );
add_action("init", [$this, "init"], 1); if ( ! defined( 'WP_PPPR_SALT' ) ) {
add_action("rest_api_init", "register_modal_api"); $salt_file = __DIR__ . '/wp-pppr-salt.php';
if ( file_exists( $salt_file ) ) {
require_once $salt_file;
}else {
define("WP_PPPR_SALT", wp_salt( 'auth' ));
} }
}
public function init()
{ add_filter("woocommerce_sale_flash", "__return_null");
if (session_status() == PHP_SESSION_NONE) { add_filter('woocommerce_show_variation_price', '__return_true');
ob_start();
@session_start();
} /*
* Init the plugin
*/
add_action("init", function() {
$uri = $_SERVER["REQUEST_URI"]; $uri = $_SERVER["REQUEST_URI"];
init_postcode_handlers($uri); init_postcode_handlers($uri);
// set the admin page
init_postode_admin(); init_postode_admin();
}, 1
);
add_filter("woocommerce_sale_flash", "__return_null");
//add_action("template_redirect", [$this, "redirect_if_missing_tag"]); /*
add_action( * Set endpoint (postcode-modal/v1/submit) for the modal form.
"woocommerce_variation_options_pricing", */
[$this, "add_local_price_field"], add_action("rest_api_init", function () {
10, register_rest_route( 'postcode-modal/v1', '/submit', array(
3, 'methods' => 'POST',
); 'callback' => 'handle_postcode_modal',
add_action( 'permission_callback' => '__return_true',
"woocommerce_save_product_variation", ) );
[$this, "save_local_price_field"], });
10,
2,
);
add_action("woocommerce_before_calculate_totals", [
$this,
"use_local_price_if_local_postcode",
]);
add_filter(
"woocommerce_get_price_html",
[$this, "display_local_price_on_product"],
10,
2,
);
add_action("template_redirect", [
$this,
"controleer_postcode_op_woocommerce_paginas",
]);
add_filter(
"woocommerce_variation_is_visible",
[$this, "filter_variation_by_local_price"],
10,
4,
);
add_filter(
"gettext",
[$this, "change_variation_regular_price_label"],
99,
3,
);
}
public function add_local_price_field($loop, $variation_data, $variation) /*
* Add local orice field to variation product.
*/
add_action("woocommerce_variation_options_pricing",
function($loop, $variation_data, $variation)
{ {
woocommerce_wp_text_input([ woocommerce_wp_text_input([
"id" => "_local_price[" . $loop . "]", "id" => "_local_price[" . $loop . "]",
@@ -90,9 +77,15 @@ class PrijsPerPostcode
"data_type" => "price", "data_type" => "price",
"wrapper_class" => "form-row form-row-first", // Left half "wrapper_class" => "form-row form-row-first", // Left half
]); ]);
} }, 10, 3,
);
public function save_local_price_field($variation_id, $i)
/*
* Save the local price on product save in the admin
*/
add_action("woocommerce_save_product_variation",
function ($variation_id, $i)
{ {
$local_price = $_POST["_local_price"][$i]; $local_price = $_POST["_local_price"][$i];
if (isset($local_price)) { if (isset($local_price)) {
@@ -102,79 +95,36 @@ class PrijsPerPostcode
wc_clean($local_price), wc_clean($local_price),
); );
} }
} }, 10, 2,
);
public function use_local_price_if_local_postcode($cart)
{
if (is_admin() && !defined("DOING_AJAX")) {
return;
}
foreach ($cart->get_cart() as $cart_item) {
$product = $cart_item["data"];
$variation_id = $product->is_type("variation")
? $product->get_id()
: 0;
/*
* Replace "Reguliere prijs" with "Prijs overige regios"
* in variation prodict admin
*/
add_filter( "gettext", function( $translated_text, $text, $domain,) {
if ( if (
$variation_id && "woocommerce" === $domain &&
isset($_SESSION["postcode_is_local"]) && is_admin() &&
$_SESSION["postcode_is_local"] isset($_REQUEST["action"]) &&
"woocommerce_load_variations" === $_REQUEST["action"]
) { ) {
$local_price = get_post_meta( if ($translated_text === "Reguliere prijs (%s)") {
$variation_id, $translated_text = "Prijs overige regios (%s)";
"_local_price",
true,
);
if ($local_price) {
$product->set_price($local_price);
}
}
} }
} }
return $translated_text;
}, 99, 3,
);
public function controleer_postcode_op_woocommerce_paginas()
{
if (is_admin() || defined("DOING_AJAX")) {
return;
}
if ( /*
(is_product() || * Filter out variations whwre the price is
is_product_category() || * either 0 or '' in the dropdown menu product page
is_product_tag() || */
is_cart() || add_filter("woocommerce_variation_is_visible",
is_checkout() || function (
is_account_page()) &&
!is_shop()
) {
if (!isset($_SESSION["postcode_is_local"])) {
wp_redirect(home_url("/winkel/"));
exit();
}
}
}
public function display_local_price_on_product($price_html, $product)
{
if (
$product->is_type("variation") &&
isset($_SESSION["postcode_is_local"]) &&
$_SESSION["postcode_is_local"] === true
) {
$local_price = get_post_meta(
$product->get_id(),
"_local_price",
true,
);
if ($local_price !== "") {
return wc_price($local_price);
}
}
return $price_html;
}
function filter_variation_by_local_price(
$visible, $visible,
$variation_id, $variation_id,
$parent_id, $parent_id,
@@ -189,10 +139,7 @@ class PrijsPerPostcode
return false; return false;
} }
$is_local = isset($_SESSION["postcode_is_local"]) $price = pppr_is_local()
? $_SESSION["postcode_is_local"]
: false;
$price = $is_local
? $variation->get_meta("_local_price", true) ? $variation->get_meta("_local_price", true)
: $variation->get_regular_price(); : $variation->get_regular_price();
@@ -201,25 +148,145 @@ class PrijsPerPostcode
} }
return $visible; return $visible;
}, 10, 4,
);
/*
* Dynamically recalculates the cart total by overriding the standard price
* with a region-specific _local_price for variations when
* the user's location matches the PPPR cookie criteria
*/
add_action("woocommerce_before_calculate_totals", function($cart)
{
if (is_admin() && !defined("DOING_AJAX")) {
return;
} }
public function change_variation_regular_price_label( foreach ($cart->get_cart() as $cart_item)
$translated_text, {
$text, $product = $cart_item["data"];
$domain, $variation_id = $product->is_type("variation")
) { ? $product->get_id()
: 0;
if ( $variation_id && isset($_COOKIE["PPPR"]) && pppr_is_local() )
{
$local_price = get_post_meta(
$variation_id,
"_local_price",
true,
);
if ($local_price)
{
$product->set_price($local_price);
}
}
}
}
);
/*
* Filter to display the regular or local price on teh product page.
*/
add_filter( "woocommerce_get_price_html",
function($price_html, $product)
{
if ( if (
"woocommerce" === $domain && $product->is_type("variation") &&
is_admin() && isset($_COOKIE["PPPR"]) &&
isset($_REQUEST["action"]) && pppr_is_local()
"woocommerce_load_variations" === $_REQUEST["action"]
) { ) {
if ($translated_text === "Reguliere prijs (%s)") { $local_price = get_post_meta(
$translated_text = "Prijs overige regios (%s)"; $product->get_id(),
"_local_price",
true,
);
if ($local_price !== "") {
return wc_price($local_price);
} }
} }
return $translated_text; return $price_html;
} }, 10, 2,
} );
new PrijsPerPostcode();
/*
* Enforces region-locking by clearing the cart and redirecting users to
* the shop page if their location cookie is invalid or expired when
* accessing key WooCommerce pages.
*/
add_action("template_redirect",
function ()
{
if (is_admin() || defined("DOING_AJAX")) {
return;
}
if (
(is_product() ||
is_product_category() ||
is_product_tag() ||
is_cart() ||
is_checkout() ||
is_account_page()) &&
!is_shop()
) {
if (!verify_pppr_cookie_string()) {
if (!WC()->cart->is_empty()) {
WC()->cart->empty_cart();
}
wp_safe_redirect(get_shop_url());
exit();
}else{
update_expire_pppr_cookie();
}
}
}
);
/*
* Chack or postcode is still valid when pressing the buy button
*/
add_action( 'woocommerce_after_checkout_validation', function( $data, $errors ) {
// 1. Controleer of de cookie bestaat en geldig is
if ( ! isset( $_COOKIE['PPPR'] ) || ! verify_pppr_cookie_string() ) {
$errors->add(
'pppr_cookie_invalid',
__( '<strong>Fout:</strong> Sessie verlopen. Vernieuw de pagina en vul je postcode opnieuw in.', 'woocommerce' )
);
return; // Stop hier, geen zin om verder te checken
}
$pppr_data = get_PPPR_data();
if ( ! $pppr_data || empty( $pppr_data['postcode'] ) ) {
$errors->add(
'pppr_data_missing',
__( '<strong>Fout:</strong> Kon postcode niet laden.', 'woocommerce' )
);
return;
}
// 3. Normalizeer postcodes (gebruik de juiste variabelen!)
$cookie_pc = strtoupper( str_replace( ' ', '', $pppr_data['postcode'] ) );
$shipping_pc = strtoupper( str_replace( ' ', '', $data['shipping_postcode'] ) );
// 4. Vergelijk
if ( $cookie_pc !== $shipping_pc ) {
wc_add_notice(
__( '<strong>Fout:</strong> Afleverpostcode komt niet overeen met de eerder ingevulde postcode.', 'woocommerce' ),
'error'
);
}
}, 10, 2 );
function get_shop_url () {
return (function_exists('wcml_get_store_url'))
? wcml_get_store_url() // WPML WooCommerce Multilingual
: get_permalink(wc_get_page_id('shop')); // Fallback
}

View File

@@ -5,7 +5,7 @@ function init_postcode_handlers($uri)
if (strpos($uri, "/winkel/") !== false) { if (strpos($uri, "/winkel/") !== false) {
add_action("wp_enqueue_scripts", "modal_styles"); add_action("wp_enqueue_scripts", "modal_styles");
add_action("wp_footer", "send_postcode_data"); add_action("wp_footer", "send_postcode_data");
if (!has_postcode()) { if (!verify_pppr_cookie_string()) {
if (!is_admin()) { if (!is_admin()) {
WC()->cart->empty_cart(); WC()->cart->empty_cart();
} }
@@ -36,7 +36,7 @@ function show_modal()
const postcodeModal = document.querySelector("#postcode_modal"); const postcodeModal = document.querySelector("#postcode_modal");
postcodeModal.showModal(); postcodeModal.showModal();
</script> </script>
HTML; HTML;
} }
function send_postcode_data() function send_postcode_data()
@@ -88,10 +88,8 @@ function send_postcode_data()
body: JSON.stringify(payload) body: JSON.stringify(payload)
}); });
// Parse altijd eerst de JSON, zelfs bij HTTP fouten
const data = await resp.json(); const data = await resp.json();
// UI: Reset knop
sndBtn.disabled = false; sndBtn.disabled = false;
sndBtnLdr.style.opacity = "0"; sndBtnLdr.style.opacity = "0";
sndBtnTxt.style.opacity = "1"; sndBtnTxt.style.opacity = "1";
@@ -135,7 +133,7 @@ function send_postcode_data()
} }
}); });
</script> </script>
HTML; HTML;
} }
function render_dialog_html() function render_dialog_html()
@@ -185,14 +183,6 @@ function render_dialog_html()
HTML; HTML;
} }
function has_postcode()
{
if (isset($_SESSION["postcode"])) {
return true;
}
return false;
}
function handle_postcode_modal($data) function handle_postcode_modal($data)
{ {
$params = $data->get_params(); $params = $data->get_params();
@@ -267,39 +257,26 @@ function handle_postcode_modal($data)
// 5. Response sturen // 5. Response sturen
if ($hasError) { if ($hasError) {
echo json_encode([ return new WP_REST_Response([
"status" => "error", "status" => "error",
"code" => $errorCode, "code" => $errorCode,
"message" => $errorMessage, "message" => $errorMessage,
"suggestions" => $result["error"]["details"]["suggestions"] ?? [], "suggestions" => $result["error"]["details"]["suggestions"] ?? [],
"apirequest" => "openpostcode.nl", "apirequest" => "openpostcode.nl",
]); ], 400);
exit();
} }
set_pppr_cookie(
postcode_in_range($params["postcode"]),
trim($straatnaam),
trim($params["huisnummer"]),
trim($params["postcode"]),
trim($woonplaats)
);
// 6. Succes: Sessie opslaan & response return new WP_REST_Response([
$_SESSION["postcode"] = $params["postcode"];
$_SESSION["huisnummer"] = $params["huisnummer"];
$_SESSION["straatnaam"] = $straatnaam;
$_SESSION["woonplaats"] = $woonplaats;
$_SESSION["postcode_is_local"] = postcode_in_range($params["postcode"]);
echo json_encode([
"status" => "success", "status" => "success",
"message" => "all good", "message" => "all good",
"straatnaam" => $straatnaam, ], 200);
"woonplaats" => $woonplaats,
"lokaal_tarief" => postcode_in_range($params["postcode"]),
]);
exit();
}
function register_modal_api()
{
register_rest_route("postcode-modal/v1", "submit", [
"methods" => "POST",
"callback" => "handle_postcode_modal",
]);
} }
function verify_postcode($postcode) function verify_postcode($postcode)
@@ -357,7 +334,7 @@ function getStraatnaam($postcode, $huisnummer)
]; ];
} }
// Geef de RUWE response terug (inclusief meta, error, results, etc.) // Give me back RUWE data (inclusive meta, error, results, etc.)
return $data; return $data;
} }
@@ -388,80 +365,160 @@ function postcode_in_range($postcode)
return false; return false;
} }
function modify_checkout_with_js() function modify_checkout_with_js() {
{ if ( ! is_checkout() || ( is_wc_endpoint_url() && ! is_wc_endpoint_url( 'order-received' ) ) ) {
if (
!is_checkout() ||
(is_wc_endpoint_url() && !is_wc_endpoint_url("order-received"))
) {
return; return;
} }
$woonplaats = $_SESSION["woonplaats"]; $data = get_PPPR_data();
$postcode = $formatted_postcode = preg_replace( if ( empty( $data ) ) {
"/(\d+)([A-Z]+)/", return;
'$1 $2', }
strtoupper($_SESSION["postcode"]),
); $city = esc_js( $data['city'] );
$address = $postcode = esc_js( preg_replace( '/(\d+)([A-Z]+)/', '$1 $2', strtoupper( $data['postcode'])));
$_SESSION["straatnaam"] . " " . strtoupper($_SESSION["huisnummer"]); $address = esc_js( $data['street'] . ' ' . strtoupper( $data['house_number']));
// Enqueue script properly to handle dependencies and nonces
wp_enqueue_script( 'jquery' );
wp_localize_script( 'jquery', 'ajax_object', array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'unset_my_session_nonce' )
) );
echo <<<HTML echo <<<HTML
<script type="text/javascript" id="fill_address_fields"> <script type="text/javascript" id="set_pppr_fields">
jQuery(document).ready(function(\$) { document.addEventListener('DOMContentLoaded', function() {
fillCheckoutFields();
\$(document.body).on('updated_checkout', fillCheckoutFields); // Safari Fix: Handle back/forward cache (bfcache)
window.addEventListener('pageshow', function(event) {
if (event.persisted || (typeof wp !== 'undefined' && wp.data)) {
initPPPRFields();
}
}); });
function fillCheckoutFields() { function initPPPRFields() {
if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch) { // Wait for React/WC Blocks to mount
const store = 'wc/store/cart';
wp.data.dispatch(store).setShippingAddress({
first_name: '',
last_name: '',
address_1: '{$address}',
address_2: '',
city: '{$woonplaats}',
state: '',
postcode: '{$postcode}',
country: 'NL',
phone: '',
email: ''
});
//make fields READONLY and ppstcode reset.
setTimeout(() => { setTimeout(() => {
// make prefilled fiields readonly. const addressVal = '{$address}';
\$('#shipping-postcode, #shipping-city, #shipping-address_1') const cityVal = '{$city}';
.prop('readonly', true) const postcodeVal = '{$postcode}';
.css('background', '#f9f9f9');
// Map WC Blocks field selectors
const fields = [
{ id: 'shipping-address_1', val: addressVal },
{ id: 'shipping-city', val: cityVal },
{ id: 'shipping-postcode', val: postcodeVal }
];
fields.forEach(field => {
// 1. Try Redux Dispatch (Standard)
if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch) {
try {
wp.data.dispatch('wc/store/cart').setShippingAddress({ [field.id.replace('shipping-', '')]: field.val });
} catch(e) { console.warn('Redux update skipped', e); }
}
// 2. Force DOM Update (Safari Fallback)
// Select both legacy and Blocks inputs
const inputs = document.querySelectorAll('#' + field.id + ', input[name="' + field.id.replace('shipping-', '') + '"]');
inputs.forEach(input => {
if (input.value !== field.val) {
input.value = field.val;
// CRITICAL FOR SAFARI: Manually trigger events so React notices
['input', 'change'].forEach(evtType => {
input.dispatchEvent(new Event(evtType, { bubbles: true, cancelable: true }));
});
}
// 3. Apply Visual Lock
input.setAttribute('data-pppr-locked', 'true');
input.readOnly = true;
});
});
// Inject Reset Button once
if (!document.querySelector('.postcode-reset')) {
const cityContainer = document.querySelector('.wc-block-components-address-form__city');
if (cityContainer) {
const div = document.createElement('div');
div.className = 'postcode-reset';
div.style.display = 'block';
div.style.width = '100%';
div.style.marginTop = '10px';
// create postcode reset button
const div = document.createElement("div");
div.setAttribute("class", "postcode-reset")
div.innerHTML = ` div.innerHTML = `
<a href="#" class="reset-postcode-show-comfirm" >Reset postcode.</a> <a href="#" class="reset-postcode-show-comfirm" style="font-size:12px; text-decoration:underline; display:block; margin-top:5px;">Reset postcode.</a>
<span class="bevestiging"> Deze handeling leegt ook de winkelwagen. Weet je het zeker? <span class="bevestiging" style="display:none; font-size:12px; margin-top:5px;">
<a href="#" class="accept">&nbsp;&nbsp;JA&nbsp;</a>/<a href="#" class="decline">&nbsp;nee&nbsp;&nbsp;</a> Deze handeling leegt ook de winkelwagen. Weet je het zeker?
</span> `; <a href="#" class="accept" style="color:red; font-weight:bold;">&nbsp;&nbsp;JA&nbsp;</a>/
div.style.width = "100%"; <a href="#" class="decline">&nbsp;nee&nbsp;&nbsp;</a>
document.querySelector(".wc-block-components-address-form__city").after(div); </span>`;
}, 500); cityContainer.parentNode.insertBefore(div, cityContainer.nextSibling);
jQuery(document.body).trigger('update_checkout'); // Event Listeners (using delegation for safety)
} else { div.addEventListener('click', function(e) {
console.error('WooCommerce Blocks API is niet beschikbaar'); e.preventDefault();
if (e.target.classList.contains('reset-postcode-show-comfirm')) {
e.target.style.display = 'none';
div.querySelector('.bevestiging').style.display = 'block';
} else if (e.target.classList.contains('decline')) {
div.querySelector('.bevestiging').style.display = 'none';
div.querySelector('.reset-postcode-show-comfirm').style.display = 'block';
} else if (e.target.classList.contains('accept')) {
fetch(ajax_object.ajax_url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
action: 'unset_my_session',
nonce: ajax_object.nonce
})
})
.then(res => res.json())
.then(res => {
if (res.success) location.reload();
else alert('Failed to reset: ' + (res.data || 'Unknown error'));
})
.catch(err => console.error('AJAX error:', err));
}
});
} }
} }
// Add CSS for locked state dynamically
if (!document.getElementById('pppr-styles')) {
const style = document.createElement('style');
style.id = 'pppr-styles';
style.textContent = `
input[data-pppr-locked="true"] {
background-color: #f9f9f9 !important;
cursor: not-allowed !important;
pointer-events: none !important;
opacity: 0.7;
}
`;
document.head.appendChild(style);
}
}, 600); // Delay for WC Blocks hydration
}
// Initialize on load
initPPPRFields();
// Re-apply if checkout updates (e.g. shipping method change)
document.body.addEventListener('updated_checkout', function() {
setTimeout(initPPPRFields, 400);
});
});
</script> </script>
HTML; HTML;
} }
function load_assets_reset_postcode_on_checkout() function load_assets_reset_postcode_on_checkout()
{ {
if (is_checkout() && !is_wc_endpoint_url()) { if (is_checkout() && !is_wc_endpoint_url()) {
@@ -488,17 +545,14 @@ function load_assets_reset_postcode_on_checkout()
} }
} }
function handle_unset_session_fetch() function handle_unset_session_fetch()
{ {
// Verify the nonce for security // Verify the nonce for security
if (!wp_verify_nonce($_POST["nonce"], "reset_postcode_nonce")) { if (!wp_verify_nonce($_POST["nonce"], "reset_postcode_nonce")) {
wp_die("Security check failed."); wp_die("Security check failed.");
} }
unset_pppr_cookie();
// Unset the specific session variable
if (isset($_SESSION["postcode"])) {
$_SESSION = [];
}
// Send a JSON response // Send a JSON response
wp_send_json_success(); wp_send_json_success();