0

I need to set up a custom product price after calculation. I am doing the code below and it is working well but it just get the first digit from the whole number

add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,10);
function wdm_add_item_data($cart_item_data, $product_id) {

    global $woocommerce;
    $new_value = array();
    $new_value['_custom_options'] = '678';

    if(empty($cart_item_data)) {
        return $new_value;
    } else {
        return array_merge($cart_item_data, $new_value);
    }
}

For that being said, the custom price is just set 6, which should rather be 678. It is so weird, can anybody know why and how to fix it? Thanks a lot.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Jack Trinh
  • 55
  • 7

1 Answers1

1

You used woocommerce_add_cart_item_data to add custom meta is right but you didn't set custom price to product price.

function wdm_add_item_data( $cart_item_data, $product_id ) {
    
    $cart_item_data[ "_custom_options" ] = 678
    return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'wdm_add_item_data', 10, 2 );

Use the woocommerce_before_calculate_totals action hook to set custom price to product in the cart.

function woocommerce_custom_price_to_cart_item( $cart_object ) {  
    foreach ( $cart_object->cart_contents as $key => $value ) {
        if( isset( $value["_custom_options"] ) ) {
            $value['data']->set_price($value["_custom_options"]);
        }
    }  
}
add_action( 'woocommerce_before_calculate_totals', 'woocommerce_custom_price_to_cart_item', 10 );
Bhautik
  • 11,125
  • 3
  • 16
  • 38