Мой код выглядит следующим образом:
Код: Выделить всё
function add_charity_hidden_field() {
echo '';
}
add_action('woocommerce_after_order_notes', 'add_charity_hidden_field');
add_action('woocommerce_before_add_to_cart_button', 'my_custom_checkout_field');
function my_custom_checkout_field() {
echo 'Charity';
echo '
document.addEventListener("DOMContentLoaded", function () {
// Create a hidden input to store charity data
const charityInput = document.createElement("input");
charityInput.type = "hidden";
charityInput.name = "charity_data"; // The name will be used to reference in PHP
charityInput.id = "charity_data"; // Optional: Assign an ID to the input
// Append the hidden input to the WooCommerce checkout form
const checkoutForm = document.querySelector("form.checkout");
if (checkoutForm) {
checkoutForm.appendChild(charityInput);
}
// Function to handle charity data updates
const updateEvent = data => {
// Convert the charity data to a string and set it as the value of the hidden input
charityInput.value = JSON.stringify(data);
console.log("Charity data updated:", data); // Debugging: Log the data for confirmation
}
// Function to handle the removal of charity data (if applicable)
const removeEvent = () => {
charityInput.value = ""; // Clear the hidden input if the event is removed
console.log("Charity data removed"); // Debugging: Log the removal
}
// Function to handle the incoming message from the widget
const handleMessage = e => {
// Ensure the message is coming from the correct origin
if (e.origin !== "https://www.pledge.to") return;
// Parse the incoming message
const message = JSON.parse(e.data);
// Handle the actions based on the message type
switch (message.action) {
case "updateEvent":
return updateEvent(message.data);
case "removeEvent":
return removeEvent();
}
}
// Add the message event listener to listen for the charity widgets data
addEventListener("message", handleMessage);
});
';
echo '';
}
// Store custom field
function save_my_custom_checkout_field( $cart_item_data, $product_id ) {
if (isset($_POST['charity_data']) && !empty($_POST['charity_data'])) {
// Sanitize the charity data
$cart_item_data = sanitize_text_field($_POST['charity_data']);
echo $cart_item_data;
} else {
echo "No charity";
}
return $cart_item_data;
}
add_action( 'woocommerce_add_cart_item_data', 'save_my_custom_checkout_field', 10, 2 );
Подробнее здесь: https://stackoverflow.com/questions/791 ... s-php-file