WordPress: controllare la lunghezza del riassunto dei post

WordPress: controllare la lunghezza del riassunto dei post

La funzione di WordPress the_excerpt() visualizza il riasssunto di un post andando a visualizzare solo un determinato numero di caratteri. Il problema insito nel comportamento predefinito di questa funzione è che spesso una frase può risultare tagliata in un certo punto o anche in corrispondenza di una parola. Vediamo come risolvere questo problema.

Aggiungete il seguente codice al vostro file functions.php:


function display_excerpt($length) { 
	global $post;
	$text = $post->post_excerpt;
	if ( '' == $text ) {
		$text = get_the_content('');
		$text = apply_filters('the_content', $text);
		$text = str_replace(']]>', ']]>', $text);
	}
	$text = strip_shortcodes($text);
	$text = strip_tags($text);

	$text = substr($text,0,$length);
	$excerpt = reverse_strrchr($text, '.', 1);
	if( $excerpt ) {
		echo apply_filters('the_excerpt',$excerpt);
	} else {
		echo apply_filters('the_excerpt',$text);
	}
}


function reverse_strrchr($haystack, $needle, $trail) {
    return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}

Quindi potete usare la funzione display_excerpt() nel vostro tema passandogli come parametro la lunghezza (in caratteri) del riassunto del post:


<?php display_excerpt(100); ?>
Torna su