Question

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(); ?>
Was it helpful?

Solution

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' )
        );
    }
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top