Using the latest version of woocommerce V4.01 in WordPress v5.4 I have been trawling for ages through the internet and do not seem to be able to find a working answer.
When adding an item to the cart via URL link, I need to override the cart price and have the new price entered.
Here is what I have on my functions page
function add_custom_price( $cart_object ) {
$target_product_id = 6048;
if ( !isset( $_GET[ 'add-to-cart' ] ) ) //** this is the product id sent through
$add_to_cart = esc_attr( $_GET[ 'add-to-cart' ] );
if ( $add_to_cart = $target_product_id ) {
$domain_name_meta = esc_attr( $_GET[ 'domain_name_meta' ] ); //**the domain with extension sent through
$reg = strtolower( substr( $domain_name_meta, -4 ) );
$ext = ".com";
if ( strcmp( $reg, $ext ) !== 0 ) {
$custom_price = 10;
} else {
$custom_price = 12;
}
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item[ 'product_id' ] == $target_product_id ) {
$cart_item[ 'data' ]->price = $custom_price;
$found = true;
$cart_item[ 'data' ]->set_price( $custom_price );
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
The above works but not correctly and has the following issue:
I have checked the strpos
statement and it works fine. so the custom_price should set to 12 if the strpos
statement is true (Which it is if I add a .com domain) but it keeps entering the false value of 10
Been pulling my hair out on this one
Any advice greatly appreciated.
Many thanks