Vuoi impostare un limite di caratteri per l'estratto del tuo post in WordPress? Questo snippet ti aiuta a impostare un limite per l'estratto del tuo post e rimuove anche tutto ciò che segue l'ultima frase all'interno dell'estratto. In questo modo l'estratto NON verrà interrotto a metà frase.
<?php
// Variable & intelligent excerpt length.
function print_excerpt($length) { // Max excerpt length. Length is set in characters
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); // optional, recommended
$text = strip_tags($text); // use ' $text = strip_tags($text,'<p><a>'); ' if you want to keep some tags
$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);
}
}
// Returns the portion of haystack which goes until the last occurrence of needle
function reverse_strrchr($haystack, $needle, $trail) {
return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}
?>
Ecco un esempio di come utilizzare la funzione nei modelli del tuo tema.
<?php print_excerpt(50); ?>
Nota: Se questa è la prima volta che aggiungi snippet di codice in WordPress, consulta la nostra guida su come copiare / incollare correttamente snippet di codice in WordPress, in modo da non rompere accidentalmente il tuo sito.
Se ti è piaciuto questo snippet di codice, prendi in considerazione la lettura dei nostri altri articoli sul sito come: I migliori page builder di WordPress (confrontati).
Grazie per quanto sopra. Ho aggiunto lo snippet utilizzando il plugin per snippet di codice.
Dove dovrei metterlo però: