WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] editing human_time_diff() (3 posts)

  1. Gillbergh
    Member
    Posted 5 months ago #

    So I want to edit the human_time_diff() function so that when it is between 1-15 minutes it says "a few minutes ago" and when it is 30-59 minutes it says "a half hour ago".

    I can't figure it out myself, has anyone done this on their site? let me know thank you

  2. nickohrn
    Member
    Posted 5 months ago #

    Unfortunately human_time_diff doesn't have a filter that you can hook into to provide what you're looking for. The best thing you can probably do is copy the function code itself into a new function and use that instead:

    <?php
    
    function custom_human_time_diff( $from, $to = '' ) {
    	if ( empty( $to ) )
    		$to = time();
    
    	$diff = (int) abs( $to - $from );
    
    	if ( $diff < 15 * MINUTE_IN_SECONDS ) {
    		$since = __( 'a few minutes ago' );
    	}  elseif ( $diff < HOUR_IN_SECONDS ) {
    		$since = __( 'a half hour ago' );
    	} elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
    		$hours = round( $diff / HOUR_IN_SECONDS );
    		if ( $hours <= 1 )
    			$hours = 1;
    		$since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
    	} elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
    		$days = round( $diff / DAY_IN_SECONDS );
    		if ( $days <= 1 )
    			$days = 1;
    		$since = sprintf( _n( '%s day', '%s days', $days ), $days );
    	} elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
    		$weeks = round( $diff / WEEK_IN_SECONDS );
    		if ( $weeks <= 1 )
    			$weeks = 1;
    		$since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
    	} elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
    		$months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
    		if ( $months <= 1 )
    			$months = 1;
    		$since = sprintf( _n( '%s month', '%s months', $months ), $months );
    	} elseif ( $diff >= YEAR_IN_SECONDS ) {
    		$years = round( $diff / YEAR_IN_SECONDS );
    		if ( $years <= 1 )
    			$years = 1;
    		$since = sprintf( _n( '%s year', '%s years', $years ), $years );
    	}
    
    	return $since;
    }

    I've tried to meet your requirements with the above, but you might need to make modifications to cover the case of 16 - 29 minutes (which you didn't explicitly mention in your original post).

  3. Gillbergh
    Member
    Posted 5 months ago #

    thank you so much for your help!

Reply

You must log in to post.

About this Topic

Tags

No tags yet.