WordPress.org

Ready to get started?Download WordPress

Forums

Human Time Function Help (4 posts)

  1. sahaskatta
    Member
    Posted 3 years ago #

    I checked out the native human_time_diff function in WP, but I need some help.

    The example on that page is the following:
    <?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?>

    It shows the timestamp in relative to "days". How can I tweak it to automatically switch between the following pseudocode:

    if time < 1 hour
    echo minutes
    elseif time < 1 day
    echo hours
    elseif time < 7 days
    echo days
    elseif time < 30 days
    echo weeks
    elseif time < 365 days
    echo months
    elseif time >- 365 days
    echo years

    I'm aware that there are plugins, but I'm trying to keep bloat minimal by writing a simple function that I can throw into functions.php. Could someone please give me a example of how to tweak that?

  2. There's a more powerful version of human_time_diff() sitting on Trac:

    http://core.trac.wordpress.org/ticket/9272
    http://core.trac.wordpress.org/attachment/ticket/9272/9272.patch

    Here it is in non-patch form:

    http://wordpress.pastebin.com/11Rr8Sn4

    Just copy/paste that into functions.php and rename the function to something else to avoid colliding with the original.

  3. sahaskatta
    Member
    Posted 3 years ago #

    Just to make things simpler for those looking for help, here's how I managed to get it to work. (Thanks to Alex)

    1) Grab the code from the pastebin link above.
    2) Paste it into functions.php
    3) Rename the function from human_time_diff to relative_time
    4) Look for the place you normally use <?php the_time(); ?>
    5) Replace it with <?php echo relative_time(get_the_time('U'), current_time('timestamp')) . ' ago'; ?>

    This will automatically produce nearly perfect results for "time ago" dates taking seconds, minutes, hours, days, weeks, months, and years into account.

  4. rhythmdoctor
    Member
    Posted 3 years ago #

    Thank you - This was perfect. Was looking for an answer on this for days :)

Topic Closed

This topic has been closed to new replies.

About this Topic