0
votes

Woocommerce: $cart_item['data']->set_price is not working inside custom plugin . What i need to do ?

please see the following code .

 add_action( ‘woocommerce_before_calculate_totals’, ‘woo_add_donation’);


        function woo_add_donation($cart_object) {

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

                if($cart_item['data']->id == 21){

                    $cart_item['data']->set_price(35);
                }

            }

        }

when i add this code to my theme function.php it work , but when i add this code to my custom plugin's function.php this code is not working .When i debug i understand that upto this : if($cart_item['data']->id == 21){
code in my plugin work . But this line is not working: $cart_item['data']->set_price(35); . What i need to do ?
I saw the documentation here http://woocommerce.wp-a2z.org/oik_api/wc_productset_price/

1
if it is working in functions than it should work in plugin too. May be something wrong with your plugin code!Rohit Kishore

1 Answers

0
votes

I found a solution which is not elegant but works for my purposes.

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

function add_custom_price( $cart_object ) {
    $custom_price = 10; // This will be your custome price  
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $value['data']->price = $custom_price;
    }
}