通过URL在附加购物车上的WooCommerce自定义购物车项目价格

时间:2019-08-15 06:29:25

标签: php wordpress woocommerce cart checkout

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

当您选择产品时,它必须直接去结帐,我可以这样简单地处理:

/checkout/?add-to-cart=78

但是,由于该产品是自愿捐款,因此必须有可能超过该产品的价格。

我正在尝试:

/checkout/?add-to-cart=78&donation=200

在我的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 );

    }   
}

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

/?wc-ajax=update_order_review

将价格重置为100。

如何阻止它重新设置价格?

1 个答案:

答案 0 :(得分:2)

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

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

这是通过网址中的类似/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'] );
        }

    }
}

代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。