簡體   English   中英

如何通過輸入字段更改購物車中的商品價格?

[英]How to change item price in cart by input field?

在cart.php中,我有一個輸入,用戶可以在其中輸入您自己的價格

    <input type="number" id="customPrice">
    <div data-id="<?php echo $product_id ?>" id="updateCart">Update</div>

我有一個 js 函數,用於使用產品 ID 和新價格數據發出 ajax 請求

 <script type="text/javascript">
    jQuery(function ($) {
        let customPrice = document.getElementById('customPrice');
        let price = customPrice.value;

        let updateCart = document.getElementById('updateCart');
        let id = updateCart.dataset.id


        updateCart.addEventListener('click', function () {
            $.ajax({
                url: "../wp-admin/admin-ajax.php",
                data: {action: "add_custom_price", id: id, price: 10},
                type: "POST",
                success(data) {
                    if (data) {
                        console.log(data)
                    }
                    $("[name='update_cart']").trigger("click");
                }
            });
        });

    });
</script>

在我的functions.php中我有

    function add_custom_price($cart)
{
    if (is_admin() && !defined('DOING_AJAX'))
        return;

    if (did_action('woocommerce_before_calculate_totals') >= 2)
        return;

    if (isset($_POST['price']) && $_POST['id']) {
        $price = intval($_POST['price']);
//        $id = intval($_POST['id']);

        foreach ($cart->get_cart() as $cart_item) {
            $cart_item['data']->set_price($price);
        }
    }
}

add_action('wp_ajax_add_custom_price', 'add_custom_price');
add_action('wp_ajax_nopriv_add_custom_price', 'add_custom_price');
add_action('woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);

但它不起作用。 我有 500 錯誤

我的錯誤在哪里? 或者我怎么做或其他方式? 任何建議請

你需要得到產品,然后影響價格,然后保存

 function add_custom_price($cart) {
     if (is_admin() && !defined('DOING_AJAX'))
         return;

     if (did_action('woocommerce_before_calculate_totals') >= 2)
         return;

     if (isset($_POST['price']) && $_POST['id']) {
         $price = intval($_POST['price']);
         $id = intval($_POST['id']);

         // Get product
         $product = wc_get_product($id);
         $product->set_regular_price($price);
         $product->save();
         // delete the relevant product transient
         wc_delete_product_transients( $id );
     }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM