Home Forums General Issues Calculate a member of staff’s years at company


Calculate a member of staff’s years at company

  • Hi,

    I have been trying to calculate a member of staff’s years of service and have had some success following this guide:

    I did post a message in that thread about this but noticed it looks best to open a new question (sorry about that)

    This is working great, however, I would really like to display the result as “14th Year of Service” or “3rd Year of Service” and can’t figure it out could anyone offer some guidance, please? I have been looking into it and it looks like ordinal suffix on echo $interval->y. is what I am looking to achieve.

    My PHP code is:

    <p class=”start-date”> <?php if( get_sub_field(‘startdate’) ): ?> <?php $date = get_sub_field(‘startdate’); $yearsofservice = new DateTime($date); $interval = $yearsofservice->diff(new DateTime); echo $interval->y. ‘ Year of Service’; ?></p> <?php endif; ?>

    Thank you in advance


  • Hey Darren,

    Two stages to this, first of all create a function that will add the suffix to the number, so in your theme’s functions.php file add the following:

    function add_suffix( $n ) { $suffix = date( 'S', mktime( 1, 1, 1, 1, ( (($n>=10)+($n%100>=20)+($n==0))*10 + $n%10) )); return $n . $suffix; }

    Then amend your code in the post/page by removing the line echo $interval->y. ‘ Year of Service’;

    And then replace it with the two following lines:
    $interval_with_suffix = add_suffix( $interval->y );
    echo $interval_with_suffix . ' Year of Service';

    I hope this helps, it’s been semi-tested, but no guarantees.

    If you’re interested in learning about the suffix function there’s a detailed answer here. Credit to Andrew Kozak for the solution I’ve just modified the function slightly to return the original number as well as the suffix.

    Cheers, Dan

  • Hey Dan,

    You, sir, are a hero 🙂

    That worked perfectly I literally followed your steps and it worked no problem 🙂 Thank you.

    I have just had a glance at the link you supplied too and will definitely read into it more as there is a chance we could use this type of functionality more within other areas of the site and what you have helped me with there is outstanding.

    Thank you again, very much 🙂


  • My pleasure Darren, glad it worked!

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Calculate a member of staff’s years at company’ is closed to new replies.