[英]How to get user input to override price in WooCommerce
我現在整天都在工作。 看完大量文檔后,到目前為止,這是我想出的...我想我已經接近了,但是我掛斷了想通過Cookie將變量從JS傳遞到PHP。 我在這里想念什么? 我應該提到這是通過WordPress上的WooCommerce完成的。
當有人從產品頁面的下拉菜單中選擇特定版本時,會顯示一個輸入字段。 編輯:添加了更好的上下文。 此input
是嵌套的。
<form class="variations_form cart" method="post" enctype="multipart/form-data" data-product_id="28664" data-product_variations=...">
<div class="single_variation">
<span class="price">
<div class="custom-amount-trigger">
<label>Amount</label>
<input type="number" id="custom_amount" class="custom-amount" placeholder="Enter Whole Number"/>
</div>
</div>
</form>
然后,當輸入失去焦點( onblur
)時,應該創建cookie。 此代碼是我的footer.php中已經運行的腳本的一部分。 我已將以下代碼添加到腳本中以創建cookie。 我感覺這是哪里出了問題(?)。
$(document).on('onblur','custom-amount', function(){
price = "price=" + escape(document.getElementByID("custom_amount").value) + "; ";
document.cookie = "customAmount=" + price + "path=/";
})
然后,在我的functions.php中,我有以下內容,它們應該獲取cookie信息。
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
$custom_price = $_COOKIE["customAmount"];
$target_product_ids = array (31708, 31418, 28825);
foreach ( $cart_object->cart_contents as $key => $value ) {
if ( in_array( $value['variation_id'], $target_product_ids ) ) {
$value['data']->price = $custom_price;
}
}
}
您應該這樣做:
$('#custom_amount').on('blur', function(){
price = "price=" + escape($("#custom_amount").val()) + "; ";
document.cookie = "customAmount=" + price + "path=/";
})
假設您正在使用jQuery
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.