【问题标题】:How to change item price in cart by input field?如何通过输入字段更改购物车中的商品价格?
【发布时间】:2021-06-22 20:15:22
【问题描述】:

在 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 个错误

我的错误在哪里?或者我该怎么做或其他方式?有什么好的建议

【问题讨论】:

    标签: javascript php wordpress woocommerce hook-woocommerce


    【解决方案1】:

    你需要得到产品,然后影响价格,然后保存

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

    【讨论】:

    • 缺少500但价格不变
    • 我更新了我的答案。我认为这是您看到的缓存数量。试试这个
    • 你确定 $id 是产品 id 吗?
    • 另外,在这里做一些故障排除。我在黑暗中摸索着。 “仍然无法工作”没有任何意义,而“我尝试了一个 die(print_r($product)) 并得到了这个作为响应......”是有意义的
    • 太棒了。我更新了我的答案,你会接受它作为答案吗?谢谢。按照 woocommerce 的建议,我将临时线路留在那里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    相关资源
    最近更新 更多