How to use product metadata in a price formula
Being able to use the metadata of a product inside a price formula improves the flexibility of a custom price calculator and reduces the need to create separate price formulas for different products.
The productMeta() function
When you use the productMeta() function in your price formulas, WooCommerce Product Options gets the value for a meta key associated with a product and uses it in the calculation of the price formula. The function accepts two values:
meta_key: the key used to store the requested value in the database;default: an optional value returned if no metadata was found in the database (it defaults to0if not provided).
For example, if you want to get the value associated with the service_fee meta key, you could use productMeta( 'service_fee' ). In case no value is found for the current product, the function would normally return 0. You can change the default value by passing a value of your choice as the second parameter of the function. If you use productMeta( 'service_fee', 10 ), WooCommerce Product Options will try to get the value associated with the service_fee meta key for the current product and, in case no value is found, 10 will be used instead.
Without the productMeta() function, developers would have to create a different price formula for each class of products that share the same service fee. Thanks to this function, developers could literally create a single price formula option that applies across the whole store and the service fee would only be added to the final price of products that actually have a number stored for that meta name.
Using string values
In general, strings are not allowed in a price formula because only numerical values can be evaluated in a mathematical expression. Nevertheless, WooCommerce Product Options also offers a series of logical functions that are designed to perform comparisons between values. In the context of a comparison, price formulas also accept strings. For example:
IF( [Checkboxes.selected] = "small", 10, 20 )
is a perfectly acceptable formula because Checkboxes.selected may contain a formula value that is a string and can be compared to small. If the comparison is true, the result will be 10. Otherwise, it will be 20.
For this reason, it may be useful to obtain meta values as strings for use in logical functions. For example, products may include a packaging custom field that specifies whether the packaging of the product is standard or deluxe. In that case, an overcharge for deluxe packaging could be added to the price with a formula as follows:
IF( productMeta( 'packaging', 'standard' ) = 'deluxe', 100, 0 )
This approach would be much more flexible than defining the cost for the deluxe packaging as a numeric custom field stored for each product because increasing the price of a deluxe packaging would only require changing a single formula rather than modifying every product that uses a deluxe packaging.