WordPress limit text to certain number of words


<?php 

$excerpt = get_the_excerpt();

echo wp_trim_words($excerpt, 20, '...');

?>

Custom PHP code:


<?php 

function text_words_limit( $text, $limit = 30 ) {

	$text = strip_tags( $text );

	$words_array = explode( ' ', $text, $limit );

	if( count($words_array) >= $limit ) {

		array_pop($words_array); // remove last element because it contain the rest of the text

	}

	$text_limitted = implode( ' ', $words_array );

	if(strlen($text) > $text_limitted) {

		$text_limitted .= '...';

	}

	return $text_limitted;

}

echo text_words_limit( $content, 30 );

?>

Leave a Comment