WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Code to display the latest post publication time in "time ago" (3 posts)

  1. Glisse
    Member
    Posted 1 year ago #

    Hello..ive been trying and failing for 2 days to get a code working and as a last resort i ask for your help.. usually i like to solve my own problems but this is beyond me because its a two step one and also i`m not a php literate.

    What i want: in a sidebar widget to have something like "latest post: 2 minutes ago".. there are other stats aswell in the same widget like the total posts, but those i managed to make them work..

    so the first step is to get the latest post publication time and the second is to convert it in time ago with that human_diff function.. i just could not blend these two together.. any help much appreciated

  2. vtxyzzy
    Member
    Posted 1 year ago #

    I think this will do what you want (assuming that $post->post_date is available):

    $now = date_i18n('Y-m-d H:i:s');
    $interval = date_diff(date_create($now),date_create($post->post_date));
    $msg = '';
    $sep = '';
    if($interval->days > 0) { $msg .= "$interval->days days"; $sep = ', ';}
    if($interval->h > 0) { $msg .= "$sep$interval->h Hours"; $sep = ', ';}
    if($interval->i > 0) { $msg .= "$sep$interval->i Minutes"; $sep = ', ';}
    if($interval->s > 0) { $msg .= "$sep$interval->s Seconds"; $sep = ', ';}
    echo "<p>latest post $msg ago</p>";
  3. Glisse
    Member
    Posted 1 year ago #

    Thank you so much for your reply.. at first i could not use your code at all, because my host has php 5.2 installed which does not know date_diff function.. but I installed php 5.3 on the local host, but the output was "latest post ago", i guess the $post->post_date was the probelm ..

    but working upon your code i manged to get a working one in the end

    $post= get_lastpostdate('blog');
    $convertunix= strtotime($post);
    $now = date_i18n('U');
    $diff = human_time_diff($convertunix, $now);
    echo "<p>latest post $diff ago</p>";

    thanks for your help again !

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.