• simple = – / x calculations with 2 custom fields

    Would anyone have a simple piece of code that calculates and displays a simple mathematical calculation (=-/x) between 2 custom fields?

    Thanks heaps

Viewing 8 replies - 1 through 8 (of 8 total)
  • Thread Starter Pete

    (@perthmetro)

    I’m trying to use 2 custom fields to calculate body mass index (BMI).

    BMI = weight / height^2

    Could this work?

    function bmi() {
    	global $post;
    	$height = get_post_meta( get_the_ID( $post->ID ), 'height', true );
    $weight = get_post_meta( get_the_ID( $post->ID ), 'weight', true );
    	$date1 = strval( $height );
    	$date2 = strval( $weight );
    	$bmi = $weight / $height^2;
    	return $bmi;
    }

    <?php echo bmi();?>

    You might have to typecast them to ints

    $bmi = (int)$weight / (int)$height^2;

    Got to agree. There’s no point casting the values to strings if you want to do calculations on them. I know PHP is losely typed, but there’s no reason to make it more complicated then you need to.

    You’re alos really over-complicating your function. As a starting point, there’s no need to use get_the_id() when you already have the post ID. On top of that, thos edate values are never even used, so there’s no reason to have those there at all.

    If it was me, I’d be doing something like this…

    function bmi() {
    	global $post;
    
    	return intval( get_post_meta( $post->ID, 'weight', true )) / ( intval( get_post_meta( $post->ID, 'weight', true ) ) ^ 2);
    }
    Thread Starter Pete

    (@perthmetro)

    How do i display the results on the front end?

    Thread Starter Pete

    (@perthmetro)

    Thanks I got it to work, but how do i round it off to 1 or 2 decimal places?

    That’s a basic PHP function… http://php.net/round

    Thread Starter Pete

    (@perthmetro)

    If I ask nicely would you be able to show me how it’s rounded in your code above… thanks heaps.

    The PHP manual really does say it all.

    function bmi() {
    	global $post;
    
    	$bmi = floatval( get_post_meta( $post->ID, 'weight', true )) / ( intval( get_post_meta( $post->ID, 'weight', true ) ) ^ 2);
    
            return round( $bmi, 2 );
    }

    It is that simple.

Viewing 8 replies - 1 through 8 (of 8 total)

The topic ‘simple = – / x calculations with 2 custom fields’ is closed to new replies.