woocommerce change price while add to cart

后端 未结 4 1282
情话喂你
情话喂你 2021-02-10 05:27

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

4条回答
  •  余生分开走
    2021-02-10 06:04

    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.

提交回复
热议问题