Set cart item price from a hidden input field custom price in Woocommerce 3

后端 未结 1 1469
我在风中等你
我在风中等你 2020-12-06 15:36

In Woocommerce, I used jQuery to calculate a custom price on a single product pages, and now need to pass this value to the cart.

The desired behavior is

相关标签:
1条回答
  • 2020-12-06 15:58

    First for testing purpose we add a price in the hidden input field as you don't give the code that calculate the price:

    // Add a hidden input field (With a value of 20 for testing purpose)
    add_action( 'woocommerce_before_add_to_cart_button', 'custom_hidden_product_field', 11 );
    function custom_hidden_product_field() {
        echo '<input type="hidden" id="hidden_field" name="custom_price" class="custom_price" value="20">'; // Price is 20 for testing
    }
    

    Then you will use the following to change the cart item price (WC_Session is not needed):

    // Save custom calculated price as custom cart item data
    add_filter( 'woocommerce_add_cart_item_data', 'save_custom_fields_data_to_cart', 10, 2 );
    function save_custom_fields_data_to_cart( $cart_item_data, $product_id ) {
    
        if( isset( $_POST['custom_price'] ) && ! empty( $_POST['custom_price'] )  ) {
            // Set the custom data in the cart item
            $cart_item_data['custom_price'] = (float) sanitize_text_field( $_POST['custom_price'] );
    
            // Make each item as a unique separated cart item
            $cart_item_data['unique_key'] = md5( microtime().rand() );
        }
        return $cart_item_data;
    }
    
    // Updating cart item price
    add_action( 'woocommerce_before_calculate_totals', 'change_cart_item_price', 30, 1 );
    function change_cart_item_price( $cart ) {
        if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) )
            return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;
    
        // Loop through cart items
        foreach ( $cart->get_cart() as $cart_item ) {
            // Set the new price
            if( isset($cart_item['custom_price']) ){
                $cart_item['data']->set_price($cart_item['custom_price']);
            }
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    Related: Woocommerce set_quantity crashes site when adding products to cart

    0 讨论(0)
提交回复
热议问题