Blog

WooCommerce: add to cart products with custom price

To add custom price to each cart item dynamically ( override price for each item in cart separately ) in woocommerce , you need to follow these steps mentioned bellow.
1. STEP1: Update add to cart link with custom price for shop page. Place the following code in your functions.php


     function ipe_add_to_cart_link() {
        
            global $product;
            $custom_price = 30;
        
            echo sprintf( '%s',
                    esc_url( $product->add_to_cart_url() ),
                    esc_attr( isset( $quantity ) ? $quantity : 1 ),
                    $custom_price,
                    esc_attr( $product->id ),
                    esc_attr( $product->get_sku() ),
                    esc_attr( isset( $class ) ? $class : 'button' ),
                    esc_html( $product->add_to_cart_text() )
            ); }
    add_filter('woocommerce_loop_add_to_cart_link','ipe_add_to_cart_link');

2. STEP2: Add this code in your product page add to cart form

input name="custom_price" type="hidden" value="30" 

3. STEP3: Add the bellow code in your functions.php. The code will store the ‘Custom Price’ option in the line item object for later use.


function ipe_product_custom_price( $cart_item_data, $product_id ) {
        if( isset( $_POST['custom_price'] ) && !empty($_POST['custom_price'])) {	    
            
            $cart_item_data[ "custom_price" ] = $_POST['custom_price'];    
        }
        return $cart_item_data;
       }    
    add_filter( 'woocommerce_add_cart_item_data', 'ipe_product_custom_price', 99, 2 ); 

4. STEP4: This is the main part, the code will add custom price to cart item. Place the following code in your functions.php

function ipe_apply_custom_price_to_cart_item( $cart_object ) {  
        if( !WC()->session->__isset( "reload_checkout" )) {            
            foreach ( $cart_object->cart_contents as $key => $value ) {
                if( isset( $value["custom_price"] ) ) {
                    $value['data']->price = $value["custom_price"];
                }
            }   
        }   
    }    
    add_action( 'woocommerce_before_calculate_totals', 'ipe_apply_custom_price_to_cart_item', 99 );

Leave a Reply