简体   繁体   中英

WooCommerce: Get price of chosen product variation

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.

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

add_filter('woocommerce_variation_prices_price', 'custom_variation_price_change', 9999, 2 );
add_filter('woocommerce_variation_prices_regular_price', 'custom_variation_price_change', 9999, 2 );   

function custom_variation_price_change( $price, $variation, $product ) {
   
      // add some conditional code as per your requirement  
    
       $price = $price+30;
        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM