通过 URL 添加到购物车的 WooCommerce 自定义购物车商品价格

Qar*_*Qar 3 php wordpress checkout cart woocommerce

我有一个简单的产品,默认价格值为 100。

当你选择产品时,它必须直接去结帐,我的处理方式如下:

/checkout/?add-to-cart=78
Run Code Online (Sandbox Code Playgroud)

但是,必须可以覆盖该产品的价格,因为它是志愿者的捐赠金额。

我正在尝试这个:

/checkout/?add-to-cart=78&donation=200
Run Code Online (Sandbox Code Playgroud)

在我的functions.php 中我有:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Avoiding hook repetition (when using price calculations for example)
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;



    foreach ( $cart->get_cart() as $cart ) {
        $id = $cart['data']->get_id();

        if ($id === 78 && $_GET['donation']) {
            $price = $_GET['donation'];
        }
        else {
            $price = $cart['data']->get_price();
        }

        $cart['data']->set_price( $price );

    }   
}
Run Code Online (Sandbox Code Playgroud)

当页面首次加载时,它已将价格设置为 200。但是,JS 在重新加载到此 url 后执行 ajax 调用:

/?wc-ajax=update_order_review
Run Code Online (Sandbox Code Playgroud)

将价格重置为 100。

我怎样才能阻止它重置价格?

Loi*_*tec 5

您需要在“添加到购物车”事件中将捐赠设置为自定义购物车项目数据,避免在结帐通过 ajax 刷新时丢失它。

在以下代码中,我们捕获设置为自定义购物车项目数据的捐赠值,然后将其添加到相应的购物车项目价格中。

这是通过 url 发生的,如下所示:/checkout/?add-to-cart=78&donation=200

add_filter( 'woocommerce_add_cart_item_data', 'catch_and_save_submited_donation', 10, 2 );
function catch_and_save_submited_donation( $cart_item_data, $product_id ){
    if( isset($_REQUEST['donation']) ) {
        // Get the WC_Product Object
        $product = wc_get_product( $product_id );

        // Get an set the product active price
        $cart_item_data['active_price'] = (float) $product->get_price();

        // Get the donation amount and set it
        $cart_item_data['donation'] = (float) esc_attr( $_REQUEST['donation'] );
        $cart_item_data['unique_key'] = md5( microtime().rand() ); // Make each item unique
    }
    return $cart_item_data;
}

add_action( 'woocommerce_before_calculate_totals', 'add_donation_to_item_price', 10, 1);
function add_donation_to_item_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Avoiding hook repetition (when using price calculations for example)
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $item ) {
        // Add the donation to the product price
        if ( isset( $item['donation']) && isset( $item['active_price']) ) {
            $item['data']->set_price( $item['active_price'] + $item['donation'] );
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。