2
votes

I'm trying to change the cart item price from a product variations by a bulk price defined as a product custom field (product custom meta data), when the cart item quantity reaches a specific threshold.

I'm Working from: WooCommerce: Get custom field from product variations and display it on the “additional information area” And WooCommerce: Bulk Dynamic Pricing Without a Plugin

This is what I have:

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 );
            }
        }  
    }
}

But it doesn't work, as I can't get the custom field value for the bulk price.

1

1 Answers

2
votes

In your code $variation_data['variation_id'] is not defined as $variation_data doesn't exist for woocommerce_before_calculate_totals hook… Try the following instead:

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 );
        }
    }
}

Code goes in functions.php file of your active child theme (or active theme). It should works.