Calculate between Toolset Types fields easily

Author: Aleš Sýkora, 10. 10. 2018

I have a fast tip for you today. If you need some basic math operations between your custom fields made with Types plugin, then I have a solution for you.

I need to display my custom field with price without VAT and then calculate the price with VAT. In Czech republic, VAT is 21%. I need to multiply the "price-without-vat" field with number 1.21. How can I do that?

First thing I need is my own plugin (of course you can add the function to functions.php but i don't recommend that).

I need header info for my plugin:

<?php
/**
 * Plugin Name: Calculations Shortcode
 * Description: Add shortcode calculate
 * Plugin URI: 
 * Author: Aleš Sýkora
 * Author URI: http://www.alessykora.cz/
 * Version: 1.0.2
 * License: GPL2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

And function for caculations:

add_shortcode('calculate', 'calculate_shortcode');
function calculate_shortcode($atts,$content=null) {
$content = wpv_do_shortcode($content);
$content = eval('return ' . $content . ';');
return $content ;
}

Version with rounding:

add_shortcode('calculate', 'calculate_shortcode');
function calculate_shortcode($atts=[],$content=null) {
$atts = shortcode_atts(['round' => 0], $atts );
$content = wpv_do_shortcode($content);
$content = eval('return ' . $content . ';');
$content = round($content, $atts['round']);
return $content;
}

Save the file with .PHP suffix and add it to the .ZIP file. Then open your WordPress admin and install the plugin.

activate wordpress plugin

You can download:

Plugins do not work together.

After Instalation and activation of the calculations plugin go to the Toolset settings and register the calculate shortcode

Toolset > Settings > Front-end Content > Third-party shortcode arguments

third party shortcode integration views

Now it's time to use the shortcode in view. Open your view and use it like this:

[calculate][field 1 raw]+[field 2 raw][/calculate]

Or like me, if you need to use only only Custom field:

[calculate][field 1 raw]*1.21[/calculate]

With new calculations round plugin use round option (if you need). If you do not fill the number, then it will round to 2 decimals.

[calculate round=2][field 1 raw]*1.21[/calculate]

In my case it finally looks like this:

calculate view custom fields

If your field is empty, then the plugin fail in case of empty_field * 1.21. So be sure to have conditional for displaying the calculation.

Did you successfully implemented your custom calculate shortcode in search form? Let me know in the comments below!