Last active
November 22, 2021 02:19
-
-
Save NickGreen/d92c64b0e5fa5254fe55e616376fcf0d to your computer and use it in GitHub Desktop.
Custom price based on custom field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Save custom calculated price as custom cart item data | |
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_fields_data_to_cart', 10, 2 ); | |
function save_custom_fields_data_to_cart( $cart_item_data, $product_id ) { | |
if ( CUSTOMER_IS_IN_US ) { | |
// Set the custom data in the cart item | |
$cart_item_data['custom_price'] = GET_PRICE_FROM_CUSTOM_FIELD; | |
// Make each item as a unique separated cart item | |
$cart_item_data['unique_key'] = md5( microtime().rand() ); | |
} | |
return $cart_item_data; | |
} | |
// Updating cart item price | |
add_action( 'woocommerce_before_calculate_totals', 'change_cart_item_price', 30, 1 ); | |
function change_cart_item_price( $cart ) { | |
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) ) | |
return; | |
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) | |
return; | |
// Loop through cart items | |
foreach ( $cart->get_cart() as $cart_item ) { | |
// Set the new price | |
if( isset($cart_item['custom_price']) ){ | |
$cart_item['data']->set_price($cart_item['custom_price']); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment