woocommerce change price while add to cart

后端 未结 4 2139
时光取名叫无心
时光取名叫无心 2021-02-10 05:13

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 05:49

    First of all I want to warn you that if you use price in the url of your add_to_cart link that might make your store vulnerable. If you use this in product meta that would be more secured. Anyway I'm showing you the code to achieve how to set price from the url.

    add_filter( 'woocommerce_add_cart_item', 'c_other_options_add_cart_item', 20, 1 );
    function c_other_options_add_cart_item( $cart_item ) {
    
        if (isset($cart_item['_other_options'])) :
            if( isset($cart_item['_other_options']['product-price']) )
                $extra_cost = floatval($cart_item['_other_options']['product-price']);
    
            $cart_item['data']->adjust_price( $extra_cost );
            // here the real adjustment is going on...
    
        endif;
    
        return $cart_item;
    
    }
    
    add_filter( 'woocommerce_add_cart_item_data', 'c_other_options_add_cart_item_data', 10, 2 );
    function c_other_options_add_cart_item_data($cart_item_meta, $product_id){
        global $woocommerce;
    
        $product = new WC_Product( $product_id);
        $price = $product->price;
    
        if(empty($cart_item_meta['_other_options']))
            $cart_item_meta['_other_options'] = array();
    
        $cart_item_meta['_other_options']['product-price'] = esc_attr($_REQUEST['price']) - $price;
    
    // as woocommerce allows to adjust the price (i don't know if there is any way to reset it, but this procedure works), we need to return the adjustable price 
    
        return $cart_item_meta;
    }
    

提交回复
热议问题