根据自定义字段和数量阈值更改WooCommerce购物车项目价格。

问题描述 投票:0回答:1

我想通过定义为产品自定义字段的批量价格来改变购物车中的商品价格。(产品自定义元数据),当购物车中的商品数量达到特定的阈值时。

我从工作。WooCommerce: 从产品变化中获取自定义字段,并将其显示在 "附加信息区域"还有 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 );
            }
        }  
    }
}

但它不工作,因为我不能得到自定义字段的值 为批量价格。

php wordpress woocommerce cart price
1个回答
2
投票

在你的代码中 $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 );
        }
    }
}

代码放在你的活动子主题(或活动主题)的function.php文件中。它应该工作。

© www.soinside.com 2019 - 2024. All rights reserved.