woocommerce_before_calculate_totals running priority between two plugin

I’m fairly new to WooCommerce plugin development and i’m creating my first wordpress plugin. I plugin function is to add custom message to the product with additional $400 fee when customer choose to use it. Here is my code:

/**
* Add the message as item data to the cart object
* @since 1.0.0
* @param Array $cart_item_data Cart item meta data.
* @param Integer $product_id Product ID.
* @param Integer $variation_id Variation ID.
* @param Boolean $quantity Quantity
*/
function mmdwoo_add_custom_field_item_data( $cart_item_data, $product_id, $variation_id, $quantity ) {
// Check if ‘Add Personal Laser Inscription’ is enabled
if ( isset($_POST[‘add-custom-message-checkbox’]) ) {
if( ! empty( $_POST[‘mmdwoo-custom-message-textarea’] ) ) {
// Add the item data
$cart_item_data[‘custom_message_field’] = $_POST[‘mmdwoo-custom-message-textarea’];
$product = wc_get_product( $product_id );
$price = $product->get_price(); // get the product price
$custom_message_price = 400; // the custom message price
$cart_item_data[‘total_price’] = $price + $custom_message_price; // set the new product price
}
}
return $cart_item_data;
}
add_filter( ‘woocommerce_add_cart_item_data’, ‘mmdwoo_add_custom_field_item_data’, 10, 4 );

/**
* Update the price in the cart
* @since 1.0.0
*/
function mmdwoo_before_calculate_totals( $cart_obj ) {
if ( is_admin() && ! defined( ‘DOING_AJAX’ ) ) {
return;
}

// Iterate through each cart item
foreach( $cart_obj->get_cart() as $key=>$value ) {
if( isset( $value[‘total_price’] ) ) {
$price = $value[‘total_price’];
$value[‘data’]->set_price( ( $price ) );
}
}

}
add_action( ‘woocommerce_before_calculate_totals’, ‘mmdwoo_before_calculate_totals’, 10, 1 );

The code above works perfectly, but when use together with WooCommerce Deposit and tried to have 50% discount, the calculation get wrong. The additional $400 fee is added to 50% deposit payment. I want to first add the $400 fee to original price then cut it to 50%. Example:

Product Price:$1000
W/ custom message: $1000 + $400 = $1400
50% Deposit: $700
Total Price to pay: $700

Read more here:: woocommerce_before_calculate_totals running priority between two plugin

Leave a Reply

Your email address will not be published. Required fields are marked *