PHP Math and WordPress Custom Keys by eckert
I was inputting numbers as custom keys in a WordPress site and I was manually having to do some arithmetic on them.
After being more than annoyed at this repetitive task, I decided to try and figure out how to use PHP to do this for me. I’ll provide a basic example of math and then show the actual usage I came up with (along with some help from Matt Rief).
First and foremost, if you don’t know how to use custom keys, check out THIS tutorial. It’s not quite the same in this instance, but gives you a good heads up.
Ok, to set a simple problem up, let’s say you have two custom keys “start” and “end” that you want to subtract and then have the code output. Set those keys within your WP post and then implement this code into the php template (index, single, page, etc) that you want it to show up.
$start = get_post_meta($post->ID, 'start', true); $end = get_post_meta($post->ID, 'end', true); $total = $start - $end; echo $total;
The result of the subtraction should then appear where you have this code situated.
Next, let’s add some more complications. My example is a site in which I was having people weigh-in and out over a 10 week period. I wanted to output the amount and percentage of weight they lost. We can use the above code to get the amount lost, but need to add in some more to get the percentage lost and to have it appear in percentage form.
$start = get_post_meta($post->ID, 'start', true);
$end = get_post_meta($post->ID, 'end', true);
$total = $start - $end;
$perc = ($start - $end) / $start;
$calculation = (round($perc*10000)/100);
echo $total .' (' .$calculation .'%)';
What this is now doing is echoing the total, which is the amount lost, giving us a non-breaking space and then showing the percentage lost in parenthesis. The percentage lost is determined by subtracting the end weight from the beginning and then dividing that result from the original weight. We get a long decimal number that needs to be converted to a percentage, so we then use the $calculation bit to clean that up.
Lastly, we had people who did not weigh-out at the end of the challenge. Their end weight was designated by DNW. If this is the case, that throws the arithmetic off, so we want an if else statement to fix that issue.
$start = get_post_meta($post->ID, 'start', true);
$end = get_post_meta($post->ID, 'end', true);
$total = $start - $end;
$perc = ($start - $end) / $start;
$calculation = (round($perc*10000)/100);
if($end == DNW)
echo "";
else
echo $total .' (' .$calculation .'%)';
What this does is check to see if the end custom key from the post is “DNW”. If it is, then it returns nothing. Otherwise, it returns the total and percentage.