简体   繁体   中英

How to get user input to override price in WooCommerce

I've been working at this all day now. After looking through a ton of documentation this is what I've come up with so far... I think I'm close but I'm hung up on passing the variable from JS to PHP via a Cookie. What am I missing here? I should mention this is being done with WooCommerce on WordPress.

There is an input field that shows up when someone chooses a specific variation from the drop down on a product page. EDIT: Added better context. This input is nested.

<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>

Then when the input looses focus ( onblur ), it is supposed to create the cookie. This code is part of an already working script in my footer.php. I've added the code below to the script to create the cookie. I have a feeling this is where things are going wrong (?).

$(document).on('onblur','custom-amount', function(){
    price = "price=" + escape(document.getElementByID("custom_amount").value) + "; ";
document.cookie = "customAmount=" + price + "path=/";
})

Then, in my functions.php, I have the following, which should get the cookie info.

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;
        }
    }
}

You should be doing:

$('#custom_amount').on('blur', function(){
    price = "price=" + escape($("#custom_amount").val()) + "; ";
    document.cookie = "customAmount=" + price + "path=/";
 })

Assuming you are using jquery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM