首页 > 解决方案 > 根据自定义字段和数量阈值更改 WooCommerce 购物车商品价格

问题描述

当购物车项目数量达到特定阈值时,我正在尝试通过定义为产品自定义字段(产品自定义元数据)的批量价格从产品变体中更改购物车项目价格。

我的工作来自: WooCommerce:从产品变体中获取自定义字段并将其显示在“附加信息区域”</a> 和WooCommerce:无需插件的批量动态定价

这就是我所拥有的:

add_action( 'woocommerce_before_calculate_totals', 'bbloomer_quantity_based_pricing', 9999 );

function bbloomer_quantity_based_pricing( $cart, $variation_data ) {

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

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;

    //get
    $bulk_price = get_post_meta( $variation_data[ 'variation_id' ], 'bulk_price', true);

    if ( $bulk_price ) {
        $threshold1 = 6; // Change price if items > 6

        foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
            if ( $cart_item['quantity'] >= $threshold1 ) {
                $price = $bulk_price;
                $cart_item['data']->set_price( $price );
            }
        }  
    }
}

但它不起作用,因为我无法获得批量价格的自定义字段值。

标签: phpwordpresswoocommercecartprice

解决方案


在您的代码$variation_data['variation_id']中未将钩子定义为 $variation_data不存在woocommerce_before_calculate_totals...请尝试以下操作:

add_action( 'woocommerce_before_calculate_totals', 'quantity_based_bulk_pricing', 9999, 1 );
function quantity_based_bulk_pricing( $cart ) {

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

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) 
        return;

    // Define the quantity threshold
    $qty_threshold = 6;

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // Get the bulk price from product (variation) custom field
        $bulk_price = (float) $cart_item['data']->get_meta('bulk_price');

        // Check if  item quantity has reached the defined threshold
        if( $cart_item['quantity'] >= $qty_threshold && $bulk_price > 0 ) {
            // Set the bulk price
            $cart_item['data']->set_price( $bulk_price );
        }
    }
}

代码在您的活动子主题(或活动主题)的functions.php 文件中。它应该有效。


推荐阅读