# How to create a price formula for your WooCommerce products

The WooCommerce Product Options plugin comes with a Price Formula field type which you can use to create a product price calculator. This calculates a custom price for the product based on the data that the customer enters into your other product options.

## How it works (an example)

Imagine that you're selling made-to-measure curtains which are charged based on the area of fabric ordered. To achieve this, you can create a product with the following options:

**Width**(number field)**Length**(number field)**Price Formula**

The price formula field will perform a calculation that multiplies the width, length, and the cost per meter. This will then update the total price of the product.

You can create very simple or very complex price formulas, depending on your requirements. For example, if you're selling curtains then you might want to:

- Add a fixed base cost which will be added to the calculated price regardless of the curtain dimensions.
- Double the calculated price because you're selling the curtains as a pair.

You can also choose whether or not to include the main product price in the calculated price. For example, you might have entered the main price for the curtains as $200 so that you can display it as "From $200" on the product page, but you may not want to add this to the calculated price.

## Video Tutorial

## Instructions

To create a price formula, go toÂ *Products â†’ Product Options*, edit the option group that you want to add the calculation to, and create the following options:

**One or more fields.**Do not add pricing to these because that will be handled by the Price Formula field.**A Price Formula field.**

Enter the formula which will be used to calculate the price. You can use the following variables and operators. These are displayed underneath the Formula field so that you can click to add them as required:

**Product price**- use this to optionally add the main price of the product to the formula, regardless of whether 'Ignore main product price' is enabled below. This is the price for the product or variation that you entered on the 'Add/Edit Product' page.- Each of the
**Number fields**for the product (these need to be added in square brackets, e.g. [Width] or [Length]). **+ - * and /**- use these to add mathematical calculations to the formula, for example, to multiply two number fields or add the main product price.**( )**- use brackets to tell the formula which part of the calculation to make first.

## How should I use brackets in a formula?

The calculation of mathematical expressions is based on a precise convention, called order of operations. According to this convention, **parentheses** should be solved first, then **exponentiations**, then **multiplications and divisions**, and finally **additions and subtractions**. So, parentheses are designed to prioritize the calculation of an expression in the formula. Let's illustrate this with an example of a product where the customer has entered the width as 5 and the length as 10:

- Given the formula
`[Width] * [Length] + 50`

, the convention about the order of operations tells us to calculate multiplications before additions. When`[Width]`

is 5 and`[Length]`

is 10, the result is`5 * 10 + 50 = 50 + 50 = 100`

. - Let's see a slightly different formula:
`[Width] * ( [Length] + 50 )`

. The convention instructs us to calculate the expressions inside parentheses, then the multiplication.Â When`[Width]`

is 5 and`[Length]`

is 10,Â the result is`5 * ( 10 + 50 ) = 5 * 60 = 300`

.

## A simple example

The following price formula is quite simple: `[Width] * [Length] * 25`

Since multiplications have the same priority, we can calculate the result from the left to the right. We multiply the two number fields - width and length. Then, we multiply the result by 25 to get the final price.

For example, you might use this for products that you are selling by the square meter.

## A more advanced example

This price formula is more complex: `[Width] * [Length] / 10000 * 25 * 2 + [product_price]`

It might be used to sell a pair of curtains by the meter, where the customer enters the dimensions in centimeters but the fabric is priced at $25 per square meter - so the formula needs to convert the centimeters into meters! The product might also have a base price which is added regardless of the size.

You can easily recognize that the formula includes one addition and a series of multiplications and divisions. So, let's break it down:

`The series of multiplications and divisions all have the same priority and can be calculated from the left to the right.`

`[Width] * [Length]`

represents the area of the fabric, in square centimeters.- Since the price of the fabric is expressed in square meters, we need to convert square centimeters into square meters. We do so by dividing
`[Width] * [Length]`

by`10000`

- Then, we multiply the area in square meters by
`25`

, which is the price of the fabric per square meter. - Finally, we multiply the result by
`2`

because the curtains are sold in pairs.

- Once we get the result of the multiplications and divisions, we can finally add it to
`[product_price]`

, which is the base price of the product. For example, you might add a base price to cover the labor charge, which will be the same regardless of the amount of fabric ordered. (Tip: You only need to add`[product_price]`

to the formula if 'Ignore main product price' is ticked below, otherwise it will be added twice!)

As you can see, price formulas can be complex. With complex formulas, it can be useful to use redundant parentheses that have the only purpose of improving readability, while also breaking down larger formulas in smaller chunks. For example, the previous formula could be written as `(((( [Width] * [Length] ) / 10000 ) * 25 ) * 2 ) + [product_price]`

. This formula returns the same result because the parentheses do not alter the default priority assigned to multiplications and divisions by the order of operations. Nevertheless, the parentheses help break down the formula into smaller operations.

## Using different option types in price formulas

Starting from version 2.0, WooCommerce Product Options supports every type of option inside formulas. Let's go through all the possibilities you have with this new feature. We can divide option types into six different categories:

: these include option types that list more than one choice and allow your customers to select more than one choice at a time. Option types in this category are**multi-choice/multi-selection options****Checkboxes**,**Image Buttons**,**Text Labels**, and**Products**(when the display style is set to either Checkboxes or Image Buttons). The options in this category also allow to associate each choice with a value (called "formula value") that can be used in the formula when a given choice is selected (you can read more about that in the Using formula values section);: these include the option types that list more than one choice but allow your customers to select only one choice at a time. Option types in this category are**multi-choice/single-selection options****Radio Buttons**,**Dropdown Select**,**Color Swatches**, and**Products**(when the display style is set to either Radio Buttons or Dropdown Select). The options in this category also allow to associate each choice with a value (called "formula value") that can be used in the formula when a given choice is selected (you can read more about that in the Using formula values section);: these include the**text options****Text**and**Paragraph**options;: these include the**numeric options****Number**,Â**Customer Defined Price**, and**Price Formula**options;: the option type allowing your customer to upload their own files;**file upload option**: the option that allows your customer to select a date.**date option**

Depending on the category they belong to, each option type has a different set of properties that can be used inside a formula.

### Multi-choice/multi-selection options

An option with more than one choice that allows selecting multiple choices at a time has the following properties:

**If none selected**(`none`

) returns`1`

if none of the choices is selected,`0`

otherwise;**If any selected**(`any`

)Â returns`1`

if any of the choices are selected,`0`

otherwise;**If all selected**(`all`

) returns`1`

if all the choices are selected,`0`

otherwise;**Count selected**(`count`

) returns the number of choices being selected;**Min selected value**(`min`

): when formula values are associated with one or more choices, it returns the minimum value among the choices being selected;**Max selected value**(`max`

): when formula values are associated with one or more choices, it returns the maximum value among the choices being selected;**Sum of selected value**(`sum`

): when formula values are associated with one or more choices, it returns the sum of the values across all the choices being selected;**Is choice selected**(`choices.<choice_name>.selected`

) returns`1`

when the choice called`<choice_name>`

is selected,`0`

otherwise;**Value of selected choice**(`choices.<choice_name>.value`

) returns the value associated with a specific choice, if it is selected.

#### Example 1

A store sells mobile devices. On the single product page of smartphones, several accessories are listed. If customers purchase all the accessories listed on the page, they will receive a 10% discount on the cost of the main device. The **Accessories** option is a Products option, displayed as image buttons. Let's see what this formula looks like:

`IF( [Accessories.all], 0.9, 1 ) * [product_price]`

If all the choices for the option **Accessories** are selected, then the property `[Accessories.all]`

returns `1`

and the `IF()`

function returns `0.9`

, effectively reducing `[product_price]`

by 10%. To learn more about the `IF()`

function, you can read the article about logical functions.

#### Example 2

Like the previous example, the store offers the cheapest accessory for free if customers purchase all the accessories listed on the page. In this case, the formula looks as follows:

`[product_price] - IF( [Accessories.all], [Accessories.min], 0 )`

In this case, if all the choices for the option Accessories are selected, then the `[Accessories.all]`

property returns `1`

and the `IF()`

function returns `[Accessories.min]`

Â â€“ which is the price of the cheapest choice among the accessories â€“ otherwise it returns `0`

and the product price remains unaltered.

### Multi-choice/single-selection options

An option with more than one choice that allows selecting multiple choices at a time has the following properties:

**If selected**(`selected`

) returns`1`

if any choice is selected,`0`

otherwise;**Selected value**(`value`

) returns the value associated with the selected choice;**Is choice selected**(`choices.<choice_name>.selected`

) returns`1`

when the choice called`<choice_name>`

is selected,`0`

otherwise.**Value of selected choice**(`choices.<choice_name>.value`

) returns the value associated with a specific choice, if it is selected

### Text options

Text and Paragraph options have the following properties:

**characters**(`characters`

) returns the number of characters in the text box, including any non-leading and non-trailing whitespace;**words**(`words`

) returns the number of words in the text box;**lines**(`lines`

) returns the number of lines in the textbox (this property only applies to Paragraph options because text inputs are not multiline fields)

### Numeric options

Numeric options provide the simplest type of variables for price formulas, as they only return the value being input by the user or being calculated by a formula. For the sake of simplicity, we don't use the `.`

(dot) notation here and just imply that the name of the variable returns the value carried by the option. In this category of options, we can also find price formulas: like any other numeric options, even the numeric result of a formula can be used inside other formulas.

### File upload options

**File upload** options have only one property that can be used in price formulas: the **count of the files** being uploaded by the customers. This can be inserted in a formula by clicking the button corresponding to the File upload option or by typing the variable manually. For example, if Logo is the name of the file upload option, then the count property can be written as `[Logo.count]`

.

### Date options

Date options can be used in price formulas, particularly in combination with logical functions. The properties attached to each date option are:

**Number of days from today**(`daycount`

): the number of days between today and the selected day. Please note that`daycount`

can be zero when selecting today or a negative number when selecting a past date.**Year**(`year`

): the year of the selected date**Month**(`month`

): the month of the selected date, from 1 to 12**Day**(`day`

): the day of the selected date, from 1 to 31**Weekday**(`weekday`

): the day of the week, where Sundays are`1`

and Saturdays are`7`

#### Example

A website sells guided tours of an archaeological site. The price for a ticket during the weekend is 20% higher than on any other day of the week. If "Date" is the name of a Date option, we can write the following formula:

`IF( OR( EQ( [Date.weekday], 1 ), EQ( [Date.weekday], 7 ) ), 1.25, 1 ) * [product_price]`

The product price is multiplied by a factor that depends on the day of the week of the selected date: if the day is a Saturday (`7`

) or Sunday (`1`

), then the formula will use `1.25`

as a multiplying factor. Otherwise, it will use `1`

and the ticket price will stay unaltered.

## Using formula values

When using options with multiple choices â€“ regardless of whether customers can select more than one choice at a time or not â€“, it is often useful to associate a value that can be used inside a formula. This mechanism allows the definition of very advanced formulas while minimizing the number of options and formulas in a group.

Let's consider the following example. A shop sells cut-to-the-measure plywood in different thicknesses. Each thickness has a different cost factor and the total cost can be calculated as a product of `[Width]`

by `[Length]`

by the thickness factor. The shop owner can list all the different thicknesses as choices of a dropdown select option and associate with each choice a value that will be used in the formula when a given choice is selected.

In that scenario, if **Width** and **Length** are the names of the **Number options** and **Thickness** is the name of the **Dropdown option**, then the formula can be written as follows

`( [Width] * [Length] / 10000 ) * [Thickness.value]`

where the division by 10000 converts square centimeters into square meters.

As you can see, the properties of an option are written using the `.`

(dot) notation. The formula editor shows a button or a dropdown button depending on the option type to help insert the desired property in the formula. As always, you are also free to type your formula in the text area.

## Using custom variables

Price formulas are a great tool to create custom price calculators but they can get easily out of hand in terms of complexity and readability. For this reason, in version 2.0, we introduced custom variables, which allow you to define a formula, assign it a name, and reuse it anywhere in a price formula. This helps break down a complex formula into smaller, more manageable, and more readable parts and reduces the length of a formula, reducing the possibility of introducing errors that could be hard to troubleshoot.

Let's see how we can take advantage of custom variables by rewriting the previous examples. When considering the formula `( [Width] * [Length] / 10000 ) * [Thickness.value]`

, we can identify two parts: `[Width] * [Length] / 10000`

is the area in square meters and `[Thickness.value]`

is the value associated with the choice of thickness being selected by the customer. Custom variables allow us to define a custom variable, call it **Area,** and assign it the formula `[Width] * [Length] / 10000`

. Then, use `[Area]`

in the main formula, instead of the original expression. This is how it works:

- Click the "+" button under the
**Custom variables**section of the price formula option - Type a name for the variable, remembering that variables should have unique names across the whole option group
- Click the formula associated with the custom variables and use the dropdown buttons to compose the formula or type it manually as you do with the main formula.
- Now, click the main formula and use the "Custom variables" dropdown button to select the
`Area`

variable

Custom variables are particularly useful when a certain expression is used multiple times inside a formula. Not only does this reduce the length of a formula but it also allows changing it much more easily and without making avoidable mistakes. Let's consider our original formula `( [Width] * [Length] / 10000 ) * [Thickness.value]`

and let's say that we want to calculate the result differently depending on the value of `[Width] * [Length] / 10000`

. For example, if the area is more than 2 square meters then we want to add a 20% overcharge. Without using custom variables, the formula would be:

`if ( gt( [Width] * [Length] / 10000, 2 ), 1.2, 1 ) * ( [Width] * [Length] / 10000 ) * [Thickness.value]`

When using an `[Area]`

custom variable, we can simplify that formula as follows:

`if ( gt( [Area], 2 ), 1.2, 1 ) * [Area] * [Thickness.value]`

In this formula, we used two logical functions: `IF()`

and `GT()`

. If you want to learn more, please read the article about logical functions.

Thanks to custom variables, the latest formula we wrote is much easier to read and also more efficient to modify, because changing the definition of `[Area]`

will automatically change it everywhere it is used in the formula.

For more specific tips about custom variables and how to use them proficiently in your price formulas, you can read the article How to use custom variables in price formulas.

## Reserved variable names

When writing a price formula, there are certain variable names that you should avoid because they are reserved for other mathematical constants. Using such names for your options would create a conflict between your own variables and those mathematical constants and the formula parser would indicate that the formula is invalid. The reserved names are:

**PI**: the number Ï€;**E**: the Euler's number;**LN2**: the natural logarithm of 2;**LN10**: the natural logarithm of 10;**LOG2E**: the base-2 logarithm of E;**LOG10E**: the base-10 logarithm of E;**SQRT1_2**: the square root of 0.5**SQRT2**: the square root of 2

## How to create advanced mathematical formulas

Above, we have given examples of price formulas that are of a simple or medium degree of complexity. You can also create even more complex formulas using advanced mathematical operations. We have provided a separate article about how to do that.

## FAQ

### My formula is calculating the wrong price!

These are the most common reasons for a formula not working correctly:

**Have you made a mistake in the formula?**Price formulas can be complex, especially if you are adding lots of parts to the equation. If you're not confident with the math then we recommend asking an expert to check it for you.**Is the main product price being added to the total?**WooCommerce requires you to set a price for the product or variation, otherwise it will not be purchasable. You do this on the 'Add/Edit Product' page. Normally, WooCommerce will add this to the total cost of the product, even if you are using a price formula field. You can stop this from happening by ticking the 'Ignore main product price' box in the Price Formula settings.**Are you using brackets correctly?**Brackets can make or break a formula, so check these carefully. Remember - the parts of the formula in brackets will be calculated first. Learn more about how to use brackets.