Search code examples
phpadvanced-custom-fieldsdata-conversioncustom-fields

Convert a number to hours and minutes when the number is an ACF number custom field


I currently have an ACF custom field with the number of minutes. I am using the below code in my theme template to display this on my site, however I would like it to display as hours and minutes if possible instead of a number, is this possible? A lot of posts I've seen showing how to change a number to hrs/mins do not show how to include the custom field codes.

<?php echo get_post_meta($post->ID, 'length', true); ?> Minutes

I tried the below code which works when I directly put in a number, but it's not working correctly when I switch that number to the custom field

<?php
$time=the_field('length');

$hours = floor($time / 60);
$minutes = ($time % 60);

echo $hours."hr ".$minutes;
?>

When using the above code, 110 returns 1100hr 0 instead of 1hr 40


Solution

  • The issue is that you're using "the_field()" function which displays the value of the custom field. You should use "get_field()" function to retrieve the value of the custom field and store it in a variable.

    Try the following code:

    <?php
     $time = get_field('length');
     $hours = floor($time / 60);
     $minutes = ($time % 60);
    
     echo $hours."hr ".$minutes;
    ?>