根据产品元更改 WooCommerce 购物车商品价格的问题

Issue with changing WooCommerce cart item prices based on product meta

当商品小计超过3000时,需另行定价

我将其添加为产品的元字段。在 Stack Overflow 上,很久以前有人建议我以特价 woocommerce_cart_item_name

为了我的目的我稍微修改了一下:

function kia_add_subtitle_to_cart_product( $title, $cart_item ){
    $threshold = 3000; // Change price if > 3000
    $_product = $cart_item['data'];
    $meta     = $_product->get_meta( '_opt_price_var');
    $price = $_product->get_regular_price();
    $subtotal = $cart_item['quantity'] * $price;
    if (  $subtotal > $threshold && ( $meta )) {            
        $_product->set_price( $meta );       
    }
    echo $title;
}

add_filter( 'woocommerce_cart_item_name', 'kia_add_subtitle_to_cart_product', 10, 2 );

特价仅显示在购物车表格中,但未显示在购物车总计中,也未显示在结帐中,总计和结帐中的价格仍然正常,主计算器未从该过滤器中获取。

我该如何解决?如何将它也包含在主计算器中?

我尝试了可以​​响应计算器的不同挂钩 - add_actionadd_filter,有和没有 10, 2 - 不是这样。

add_action('woocommerce_before_shipping_calculator', 'kia_add_subtitle_to_cart_product',10,2);

add_action('woocommerce_before_cart_totals', 'kia_add_subtitle_to_cart_product', 10, 2 );

woocommerce_cart_item_name 挂钩在您的代码尝试中被滥用。与使用 echo 相比,过滤器挂钩应该总是 return 一些东西。

您应该改用 woocommerce_before_calculate_totals 钩子

所以你得到:

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

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
    
    // Change price if > 3000
    $threshold = 3000;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // Get regular price
        $price = $cart_item['data']->get_regular_price();

        // Subtotal = Get quantity * price
        $subtotal = $cart_item['quantity'] * $price;

        // Greater than  
        if ( $subtotal > $threshold ) {
            // Get meta
            $meta = $cart_item['data']->get_meta( '_opt_price_var', true );

            // NOT empty
            if ( ! empty ( $meta ) ) {
                // Set new price
                $cart_item['data']->set_price( $meta );
            }
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );
add_filter('woocommerce_calculated_total', 'custom_calculated_total', 10, 2);

function custom_calculated_total($total, $cart_object) {

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

        if (!WC()->cart->is_empty()):
            foreach ($cart_object->cart_contents as $key => $cart_item) {
                $meta = $cart_item['data']->get_meta('_opt_price_var');

                if ($total >= 3000 && ( $meta )) {

                    $total = $meta;
                }
            }
        endif;
        return $total;
}