I'm having issues in Wordpress Woocommerce whereby I have programmatically updated prices of products based on whatever conditions they need. Below is a simple example. I have it displaying and then adding to the cart just fine. My problem is, when the user logs out and logs back in, the cart ends up returning the full prices of the product. Either I'm updating the price incorrectly, or there is a better way to ensure the cart has the correct discounted price.
Here is what I have in functions.php
add_action('woocommerce_get_price_html','pricechanger');
function pricechanger($price){
$theid = get_the_ID();
$product = wc_get_product($theid);
$price = $product->price;
$price = //do something to the price here
//save the productid/price in session for cart
$_SESSION['pd']['$theid'] = $price;
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10, 2);
add_action( 'init', 'woocommerce_add_to_cart_action', 10);
add_action( 'init', 'woocommerce_checkout_action', 10 );
return $price;
}
Because the price wouldn't transition to the add to cart button, I've had to save them in a session. I haven't found anywhere that sends that price to the cart.
add_action( 'woocommerce_before_calculate_totals', 'woo_add_discount');
function woo_add_discount() {
if(isset($_SESSION['pd'])) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
foreach($_SESSION['pd'] as $key => $val) {
if($cart_item['data']->id == $key){
$cart_item['data']->set_price($val);
}
}
}
}
}
Help is greatly appreciated! Thanks!