PHP calculation using ACF fields
written by: Jeff McNearPHP calculation using ACF fields
Recently I was faced with a situation where I needed to add a value to an arithmetic equation using two values from ACF fields here is how I did it:
<?php if( get_field('grill_btu') ): ?>
<?php
$btu = get_field('grill_btu');
$pcap = get_field('grill_primary_capacity');
echo " ". round($btu/$pcap, 2) ."<br />";
?>
<?php endif; ?>
First I established that the “grill_btu” field was populated:
<?php if( get_field('grill_btu') ): ?>
Then the two fields needed to be declared as variables:
$btu = get_field('grill_btu');
$pcap = get_field('grill_primary_capacity');
With that done I could express those values in an equation:
echo " ". round($btu/$pcap, 2) ."<br />";
To fine out more about PHP equations see: https://www.php.net/manual/en/ref.math.php
Because we didn’t want to show more than 2 decimal points, I used the sound function – see: https://www.php.net/manual/en/function.round.php