1

I'm using this nifty timestamp function that makes the post date "1 day ago" and "five minutes ago" etc. However after a few days I want it to switch to the actual date it was written so for example: January 4th, 2020 at 4:02pm" or maybe just the option to add the time.

Here is the code that does x days ago:

function meks_time_ago() {
    return human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) ).' '.__( 'ago' );
}

<?php echo meks_time_ago(); ?>

1 Answer 1

1

In this updated version of meks_time_ago(), the human readable date/time will be returned if the published date was less than the $threshold of days ago. Otherwise, the full date and dime will be returned.

function meks_time_ago( $days_threshold = 3 ) {
    $published_date_timestamp = get_the_time( 'U' );
    $current_date             = new DateTime();
    $published_date           = new DateTime( "@$published_date_timestamp" );
    $interval                 = $published_date->diff( $current_date );
    $interval                 = intval( $interval->format( '%a' ) );

    // If the post was published more than the $threshold of days ago,
    // show the published date and time.
    if ( $interval > $days_threshold ) {
        return sprintf( '%s %s %s',
            get_the_date(),
            __( 'at', 'text-domain' ),
            get_the_time()
        );
    } else {
        // Otherwise, use the human readable time.
        return sprintf( '%s %s',
            human_time_diff( $published_date_timestamp, $current_date->getTimestamp() ),
            __( 'ago', 'text-domain' )
        );
    }
} 
2
  • 1
    very cool, thanks! how would i get rid of the time (4:25pm etc ) if I wanted to?
    – RLM
    Commented Mar 27, 2020 at 21:48
  • 1
    never mind I found it. many thanks.
    – RLM
    Commented Mar 27, 2020 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.