php - WooCommerce 自定义 Ajax 添加到购物车 : How to set a custom price?

标签 php jquery ajax wordpress woocommerce

我正在尝试从结帐时的 on_click 事件添加产品。
该产品的价格是使用外部 API 动态计算的,因此它在 woocommerce 本身中注册为价格为 0。我正在尝试将此产品添加到购物车(工作),然后将该产品的价格设置为我从 API 收到的价格(不工作)。这是相关的代码:
单击时进行 AJAX 调用:

       jQuery('#theftdaminsurance').on('click', function(){
        jQuery.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: {
            action: 'add_product_to_cart_checkout',
            // add your parameters here
            price: <?php echo $year_dam_price; ?>,
            productid: ins_product_id
        },
        success: function (output) {
        document.getElementById("loaderdiv").style.display = "none";
        jQuery(document.body).trigger("update_checkout");
        }
        });
        });
我检查了这里的所有内容,并正确地进行了调用,并传递了所有正确的信息。
这是被调用的函数:
add_action('wp_ajax_add_product_to_cart_checkout', 'add_product_to_cart_checkout');

// register the ajax action for unauthenticated users
add_action('wp_ajax_nopriv_add_product_to_cart_checkout', 'add_product_to_cart_checkout');

function add_product_to_cart_checkout() {
    $product_id = $_REQUEST['productid'];
    $price = floatval($_REQUEST['price']);
    $ebike_ids = array(17386,17385,17382,17378,17375,17372,17370,17369,17364,16132,16130,4561,4550,3490,2376);
    $found = false;
    //check if there is something in cart
    if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
        //Delete all preexisting insurance products and find qty of ebikes
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $product_idebike = $cart_item['product_id'];
            if ( ($cart_item['product_id'] == "16600") || ($cart_item['product_id'] == "16653") || ($cart_item['product_id'] == "16654") || ($cart_item['product_id'] == "16655") ||($cart_item['product_id'] == "16659") || ($cart_item['product_id'] == "16660")) {
                        WC()->cart->remove_cart_item( $cart_item_key );
            }           
        //get ebike quantity
    for ($x = 0; $x <= 14; $x++) {
        if ($product_idebike == $ebike_ids[$x]) {
            $quantity =  $cart_item['quantity'];
            break;
        }
    }
        }
            // if command is not to remove add relevant products
                if ($price != "-1") {
                WC()->cart->add_to_cart( $product_id, $quantity );
                foreach( WC()->cart->get_cart() as $cart_item ){
                    $id = $cart_item['product_id'];
                    if ($product_id == $id) {
                        $cart_item['data']->set_price( $price );
                    }
                }
                }
            
    }

}
在这里,我基本上仔细地调试了一切,一切都按预期运行,但 set_price 函数除外。我无法将产品的价格更新为 AJAX 调用中传递的价格。结帐更新后以及更新之前,价格仍为 0。我是否以错误的方式调用或使用此函数?
非常感谢你的帮助!

最佳答案

看起来你让事情变得比 Ajax 接收器函数应该复杂得多……
请注意,您可以在使用 WC_Cart add_to_cart() 方法时添加自定义购物车项目数据,因此您将添加保险价格作为自定义购物车项目数据,然后使用它来设置价格。
这是您重新访问的 Ajax PHP 接收器函数:

add_action('wp_ajax_add_product_to_cart_checkout', 'add_product_to_cart_checkout');
add_action('wp_ajax_nopriv_add_product_to_cart_checkout', 'add_product_to_cart_checkout');
function add_product_to_cart_checkout() {
    if ( isset($_POST['productid']) && isset($_POST['price']) && ! WC()->cart->is_empty() ) {
        $product_id     = intval($_POST['productid']);
        $price          = floatval($_POST['price']);
        $ebike_ids      = array(17386,17385,17382,17378,17375,17372,17370,17369,17364,16132,16130,4561,4550,3490,2376);
        $insurance_ids  = array(16600,16653,16654,16655,16659,16660);
        $found          = false;
        $ebike_quantity = 0;

        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            // Delete all preexisting insurance products
            if ( in_array( $cart_item['product_id'],  $insurance_ids ) ) {
                WC()->cart->remove_cart_item( $cart_item_key );
            }

            // Get ebikes total quantity
            if ( in_array( $cart_item['product_id'],  $ebike_ids ) ) {
                $ebike_quantity +=  $cart_item['quantity'];
            }
        }

        // If command is not to remove add insurance product with price as custom cart item data
        if ( $price >= 0 && $cart_item['insurance_price'] > 0 ) {
            WC()->cart->add_to_cart( $product_id, $ebike_quantity, 0, array(), array( 'insurance_price' => $price ) );
        }
        die();
    }
}
然后设置您将使用的价格:
// Set insurance price from custom cart item data
add_action( 'woocommerce_before_calculate_totals', 'set_insurance_price' );
function set_insurance_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
       return;

    foreach ( $cart->get_cart() as $cart_item ) {
        if( isset($cart_item['insurance_price']) && $cart_item['insurance_price'] > 0 ) {
            $cart_item['data']->set_price( $cart_item['insurance_price'] );
        }
    }
}
现在它应该可以工作了。

关于php - WooCommerce 自定义 Ajax 添加到购物车 : How to set a custom price?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65254211/

相关文章:

javascript - Rails "Load more..."而不是分页

javascript - 如何使用 smarty 模板引擎在网站上实现类似 Vista 的 Ajax 日历

php - cURL 错误 35 - 连接到 api.rkd.reuters.com 时出现未知 SSL 协议(protocol)错误 :443

javascript - 如何使用 PHP 去除 JS 注释?

php - 如何使用mysql数据(PHP)创建highchart?

javascript - 如何使 bootstrap 下拉列表可拖动?

javascript - 加载 ajax 页面内容时,Slack channel 注册按钮不显示

php - Jquery ajax 选择下拉菜单适用于 FF 和 chrome,但不适用于 IE 7-9

jquery - Bootstrap 轮播无法正常工作

javascript - 如何使用 JavaScript 延迟对数组中的每个元素执行函数?