WordPress: utilizzare il formato delle date di Twitter

Come utilizzare il formato delle date di Twitter nei nostri post in WordPress.

WordPress di Gabriele Romanato

Twitter mostra il calcolo del tempo trascorso dalla pubblicazione di un tweet usando un formato particolare che è divenuto molto popolare nel microblogging. Possiamo riprodurre questo formato anche nei nostri temi di WordPress.

Il seguente codice, da aggiungere al file functions.php, utilizza un filtro sulla funzione the_time():


function my_time_ago() {
 
	global $post;
 
	$date = get_post_time('G', true, $post);
 
	
	$chunks = array(
		array( 60 * 60 * 24 * 365 , __( 'anno', 'tuotema' ), __( 'anni', 'tuotema' ) ),
		array( 60 * 60 * 24 * 30 , __( 'mese', 'tuotema' ), __( 'mesi', 'tuotema' ) ),
		array( 60 * 60 * 24 * 7, __( 'settimana', 'tuotema' ), __( 'settimane', 'tuotema' ) ),
		array( 60 * 60 * 24 , __( 'giorno', 'tuotema' ), __( 'giorni', 'tuotema' ) ),
		array( 60 * 60 , __( 'ora', 'tuotema' ), __( 'ore', 'tuotema' ) ),
		array( 60 , __( 'minuto', 'tuotema' ), __( 'minuti', 'tuotema' ) ),
		array( 1, __( 'secondo', 'tuotema' ), __( 'secondi', 'tuotema' ) )
	);
 
	if ( !is_numeric( $date ) ) {
		$time_chunks = explode( ':', str_replace( ' ', ':', $date ) );
		$date_chunks = explode( '-', str_replace( ' ', '-', $date ) );
		$date = gmmktime( (int)$time_chunks[1], (int)$time_chunks[2], (int)$time_chunks[3], (int)$date_chunks[1], (int)$date_chunks[2], (int)$date_chunks[0] );
	}
 
	$current_time = current_time( 'mysql', $gmt );
	$newer_date = ( !$newer_date ) ? strtotime( $current_time ) : $newer_date;
 
	
	$since = $newer_date - $date;
 
	
	if ( 0 > $since ) {
		return __( 'circa', 'tuotema' );
	}
 
	
	for ( $i = 0, $j = count($chunks); $i < $j; $i++) {
		$seconds = $chunks[$i][0];
 
		
		if ( ( $count = floor($since / $seconds) ) != 0 ) {
			break;
			
		}
	}
 
	
	$output = ( 1 == $count ) ? '1 '. $chunks[$i][1] : $cāunt . ' ' . $chunks[$i][2];
 
 
	if ( !(int)trim($output) ){
		$output = '0 ' . __( 'secondi', 'tuotema' );
	}
 
	$output .= __(' fa', 'tuotema');
 
	return $output;
}
 

add_filter('the_time', 'my_time_ago');