WordPress: gestire l'assenza del riassunto nei post

Fintanto che siamo noi a creare post sui nostri siti in WordPress, it's all fun and games (come dicono gli americani), nel senso che abbiamo il pieno controllo dell'output finale. Ma quando a gestire i post sono i nostri clienti, le cose cambiano drasticamente. Una delle cose che i clienti dimenticano più spesso sono i riassunti per ciascun post. Anche se abbiamo spiegato loro l'importanza dei riassunti per l'ottimizzazione del sito (soprattutto a livello SEO), loro continuano a dimenticarli. Il povero WordPress allora cerca di rimediare estraendo un certo numero di caratteri dal contenuto del post, ma i risultati sono insoddisfacenti. Vediamo come rimediare.

Questa funzione, da inserire nel file functions.php, genera un riassunto dei post sia nel caso che questo sia stato impostato sia nell'eventualità contraria:


function my_excerpt($excerpt = '', $excerpt_length = 50, $readmore = "Leggi tutto »", $tags = '<a>', $permalink = null) {
	global $post;
	$excerpt = strip_tags($excerpt, $tags);
	$excerpt = strip_shortcodes($excerpt);
	$string_check = explode(' ', $excerpt);
	if ($permalink === null) {
		$permalink = get_permalink();
	}

	if (count($string_check, COUNT_RECURSIVE) > $excerpt_length) {
		$new_excerpt_words = explode(' ', $excerpt, $excerpt_length+1);
		array_pop($new_excerpt_words);
		$excerpt_text = implode(' ', $new_excerpt_words);
		$temp_content = strip_tags($excerpt_text, $tags);
		$excerpt = preg_replace('|\[(.+?)\](.+?\[/\\1\])?|s','',$temp_content);
		$excerpt .= ' ... <a href="' . $permalink . '">' . $readmore . '</a>';
		return $excerpt;
	} else {
		return $excerpt;
	}
	
	$excerpt .= '... <a href="' . $permalink . '">' . $readmore . '</a>';
	return $excerpt;
}

Eccone un uso pratico:


<?php $news = get_posts( array( 'numberposts' => 2, 'post_type' => 'news' ) ); ?>

<?php foreach ( $news as $post ): ?>
<?php setup_postdata($post); ?>

<!-- continua il Loop -->

<p class="excerpt">
<?php if (!empty($post->post_excerpt)): ?>
				<?php echo my_excerpt( $post->post_excerpt ); ?>
			<?php else: ?>
				<?php echo my_excerpt( get_the_content() ); ?>
<?php endif ?>
</p>
<?php endforeach; ?>
Torna su