woocommerce change price while add to cart

woocommerce

Solution

With WooCommerce 2.5 I found this to be a 2-part process. The first step is to change the run-time display of pricing when added to the cart via the woocommerce_add_cart_item filter. The second part is to set the persistent session data which is read during checkoutvia the woocommerce_get_cart_item_from_session filter.

add_filter( 'woocommerce_add_cart_item' , 'set_woo_prices');
add_filter( 'woocommerce_get_cart_item_from_session',  'set_session_prices', 20 , 3 );

function set_woo_prices( $woo_data ) {
  if ( ! isset( $_GET['price'] ) || empty ( $_GET['price'] ) ) { return $woo_data; }
  $woo_data['data']->set_price( $_GET['price'] );
  $woo_data['my_price'] = $_GET['price'];
  return $woo_data;
}

function  set_session_prices ( $woo_data , $values , $key ) {
    if ( ! isset( $woo_data['my_price'] ) || empty ( $woo_data['my_price'] ) ) { return $woo_data; }
    $woo_data['data']->set_price( $woo_data['my_price'] );
    return $woo_data;
}

Setting my_price as part of the woo_data in woocommerce_add_cart_item allows that data to be retrieved later via the session price filter. A more secure method is to not pass price in the URL and set it directly as to avoid URL price manipulation.

In my real-world implementation connecting Store Locator Plus to WooCommerce, I store per-location pricing data for each WooCommerce product in an internal table and only set/retrieve the location ID in place of 'my_price' in this example. Internal methods are used to fetch the set price from the data table in both methods above, using the location ID as a lookup and only leaving the public URL with a location ID which is not going to allow them to modify pricing.

Problem

i have a one product 1€ and use e GET parameter to change the price at runtime: ``` http://url/warenkorb/?add-to-cart=1539&price=18.45 ``` This change not the price in the basket (still remain 1€) How to achieve this. I use the following hook: ``` add_filter( 'woocommerce_add_cart_item', 'my_woocommerce_add_cart_item', 5, 1 ); function my_woocommerce_add_cart_item( $cart_item ) { if(get_post_meta( $cart_item['data']->id, 'isConfigurableProduct', true)=='1') { if(isset($_GET['price'])) { $price=$_GET['price'];//keep it simpel for testing $cart_item['data']->set_price( $price ); $_SESSION[$cart_item['data']->id]=$price; } else { $cart_item['data']->set_price($_SESSION[$cart_item['data']->id]); } } return $cart_item; } ``` Thanks

Original source