0

I want to calculate the average value (or other calculation if possible) of several custom field values in a post. For example, I have 4 custom fields in a post, custom1 to custom4, value from 1 to 4 and I want to display the average value. Is there any way to do that?

  • Yes, use get_post_meta() and run the calculation on the 4 results. What have you tried so far? We can help you debug. – Andrew Bartel May 25 '13 at 2:36
1

You can try this to fetch the custom values:

$c1 = get_post_meta( get_the_ID(), 'custom1', TRUE );   
$c2 = get_post_meta( get_the_ID(), 'custom2', TRUE );   
$c3 = get_post_meta( get_the_ID(), 'custom3', TRUE );   
$c4 = get_post_meta( get_the_ID(), 'custom4', TRUE );   

Then to calculate the average:

// check if c1, c2, c3 and c4 are all set:
if( strlen($c1) * strlen($c2) * strlen($c3) * strlen($c4) > 0 ){

    // convert the values from string to int/float:
    $c1 = 1 * $c1;
    $c2 = 1 * $c2;
    $c3 = 1 * $c3;
    $c4 = 1 * $c4;

    // calculate the average:
    $avg = ($c1 + $c2 + $c3 + $c4) / 4 ;

    // output:
    // var_dump($avg);
    printf( "The average is %.2f", $avg );    // with two decimals:


}else{
    echo " missing value! ";
}
  • Thank you for the fast answer. It works very well and output "float(7.625)". Can I display the number only, with one decimal place? – Milo May 25 '13 at 2:57
  • ok great it worked out for you. You can use various PHP functions to format your output, for example with printf() or number_format(). Please check out the updated answer. – birgire May 25 '13 at 3:06
  • I've managed to come up with my desired output. Thanks very much for the help, you are awesome :) – Milo May 25 '13 at 3:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.