fgsdfds sdfdsf
fgsdfds sdfdsf

Reputation: 41

Dynamically calculate product price based on custom fields values when added-to-cart

I found the code to add existing product:

global $woocommerce;
$woocommerce->cart->add_to_cart(16);

But I need to add product, with price that determined by 2 inputs:

  1. Age
  2. Quality

I calculate the product's price by the formula age*quality.

I know it's possible to add product with variations, but it's so many possible variations.

Is it possible to set the product price dynamically based on custom fields calculation values?

Thanks

Upvotes: 4

Views: 2734

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253901

For the cart items (when product is added-to cart), is possible to set a custom dynamic calculated price based on product custom fields values.

1) First we add in the single product pages your 2 custom fields (Here a normal text input field and a select field) for "Age" and "Quality":

// Add product custom fields inside the product add-to-cart form
add_action('woocommerce_before_add_to_cart_button', 'custom_data_hidden_fields');
function custom_data_hidden_fields() {
    echo '<div class="imput_fields custom-imput-fields">
        <label class="age_prod">Age: <br><input type="text" id="age_prod" name="age_prod" value="" /></label>
        <label class="quality_prod">Quality: <br>
            <select name="quality_prod" id="quality_prod">
                <option value="1" selected="selected">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
            </select>
        </label>
    </div><br>';
}

2) When product is add-to-cart, we save these custom post data values with the added cart item:

// Save product custom fields values after submission into the cart item data
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_data_hidden_fields', 10, 2 );
function save_custom_data_hidden_fields( $cart_item_data, $product_id ) {

    $data = array();

    if( isset( $_REQUEST['age_prod'] ) ) {
        $cart_item_data['custom_data']['age'] = $_REQUEST['age_prod'];
    }

    if( isset( $_REQUEST['quality_prod'] ) ) {
        $cart_item_data['custom_data']['quality'] = $_REQUEST['quality_prod'];
    }

    // below statement make sure every add to cart action as unique line item
    $cart_item_data['custom_data']['unique_key'] = md5( microtime().rand() );

    return $cart_item_data;
}

3) Finally in this last step, you get all necessary data from cart to make your own calculation, and to update the price for each cart item dynamically.

I have make a temporary calculation, just to show that the code is working as expected.

Here In the code below, you will have to customize the calculation to feet your needs (as you don't give any details about that in your question).
As you will see below, it's an easy step to make your own calculation, as you get your custom fields values for each cart item and also the original price of the product.

Here is the code that will make this dynamic calculation based on your custom field values:

// Replace the item price by your custom calculation
add_action( 'woocommerce_before_calculate_totals', 'add_custom_item_price', 10 );
function add_custom_item_price( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart->get_cart() as $cart_item ) {
        // Product ID
        $product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
        // Product original price
        $original_price = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->price : $cart_item['data']->get_price();
        $original_price = $item_values['data']->price; 

        ## --- Get your custom cart item data --- ##
        if( isset($cart_item['custom_data']['age']) )
            $age     = $cart_item['custom_data']['age'];
        if( isset($cart_item['custom_data']['quality']) )
            $quality = $cart_item['custom_data']['quality'];

        // CALCULATION FOR EACH ITEM:
        ## Make HERE your own calculation to feet your needs  <==  <==  <==  <==
        $new_price = $original_price + ( ($age * 0.1) + $quality );

        ## Set the new item price in cart
        if( version_compare( WC_VERSION, '3.0', '<' ) )
            $cart_item['data']->price = $new_price;
        else
            $cart_item['data']->set_price($new_price);
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Code is tested and works perfectly.

DISPLAYING THE CUSTOM PRICE IN SINGLE PRODUCT PAGE:

Read this to understand how override the WoocCommerce templates via your theme

For that you will need to edit the template single-product/price.php.

And you will need to add some javascript/jQuery to this single product page to make the product price updated, when customer will set some values in your product custom fields.
But this is another question.


Related answer: WooCommerce - Adding a custom price to each product in cart

Upvotes: 2

Related Questions