0

I am making a custom add-on for my products on my WooCommerce webshop. Everything works as it should, but I only need one thing. When customers check the checkbox on the product page, $30 must be added to the original price of the selected variation.

add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 3 );
function add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
        
        $product = wc_get_product($product_id);
        $price = $product->get_price();
        
        if ($product->is_type( 'variable' )) {
            
            $var_price = $product->get_price_html();
            
            // extra pack checkbox
            if( ! empty( $_POST['addon-card'] ) ) {
                $cart_item_data['new_price'] = $var_price + 30;
            }
            
        } else {
            
            // extra pack checkbox
            if( ! empty( $_POST['addon-card'] ) ) {
                $cart_item_data['new_price'] = $price + 30;
            }
            
        }

return $cart_item_data; 
} 

This part: if( ! empty( $_POST['addon-card'] ) ) check if the checkbox is checked.

My problem is here:

$var_price = $product->get_price_html();

// extra pack checkbox
if( ! empty( $_POST['addon-card'] ) ) {
   $cart_item_data['new_price'] = $var_price + 30;
}

The value of $var_price is just 0.

So I try to figure out how I can get the price of the chosen variation.

I have tried with get_variation_prices() and get_variation_price() but without any luck...

UPDATE I have tried to implement the code from this thread. With that code I can get the price of the chosen variation, but I can no longer add the $30.

dan_2300
  • 1
  • 1
  • May that help you [get_variation_price](https://stackoverflow.com/questions/12272733/woocommerce-get-variation-product-price) – Kiji_T May 07 '21 at 12:13
  • Thank you for your comment. I have tried to implement the code you referred to. The positive thing is that I can now find the price of the chosen variation. The problem now is that I can not plus it with the $30. – dan_2300 May 07 '21 at 12:33

1 Answers1

0

Can you please try below WooCommerce hook to change price dynamically?

add_filter('woocommerce_variation_prices_price', 'custom_variation_price_change', 10, 3 );
add_filter('woocommerce_variation_prices_regular_price', 'custom_variation_price_change', 10, 3 );   

function custom_variation_price_change( $price, $variation, $product ) {
   
      // add some conditional code as per your requirement  
    
       $price = $price+30;
        
}
David Jirman
  • 1,216
  • 12
  • 25
wpdevloper_j
  • 330
  • 2
  • 12
  • Hey. Thank you for your comment. I've tried with the code you added, but my page will crash if I use it ... I have tried to make it very simple, by just pasting the code as you made it, without adding any conditionals. – dan_2300 May 08 '21 at 07:21