The Best Way to Limit WordPress Excerpt Length Without Plugins

During the development of the WordPress themes, sometimes we need to limit the WordPress excerpt length, just like in this section I want to display 200 words, and on that section I want to display 80 words only, then how to limit the length of the excerpt? Yes of course you can write separate excerpt for each posts, but that is not flexible enough, right? Here is a way which can help you solve this problem easily without use any plugins.

1. First of all, open the functions.php, copy and paste the following php code:

// limited post words
if ( ! function_exists( 'limited_post' ) ){
	function limited_post($amount,$echo=true,$post='') {
		global $shortname;
		if ( $post == '' ) global $post;
		$postExcerpt = '';
		$postExcerpt = $post->post_excerpt;
		if (get_option($shortname.'_use_excerpt') == 'on' && $postExcerpt <> '') { 
			if ($echo) echo $postExcerpt;
			else return $postExcerpt;	
		} else {
			$limited = $post->post_content;
			$limited = preg_replace('@\]*?\].*?\[\/caption]@si', '', $limited);
			if ( strlen($limited) <= $amount ) $echo_out = ''; else $echo_out = '.';
			$limited = apply_filters('the_content', $limited);
			$limited = preg_replace('@<script[^>]*?>.*?</script>@si', '', $limited);
			$limited = preg_replace('@<style[^>]*?>.*?</style>@si', '', $limited);
			$limited = strip_tags($limited); 
			if ($echo_out == '.') $limited = substr($limited, 0, strrpos(substr($limited, 0, $amount), ' '));
			else $limited = substr($limited, 0, $amount);

			if ($echo) echo $limited,$echo_out;
			else return ($limited . $echo_out);

2. Then insert the following php code to the place where you want to display the WordPress excerpt, or just replace the default

<p><?php limited_post(100); ?></p>

The number is the words you want to display there, if you want to display 150 words, then replace the 100 with 150. That’s it.

Leave a Reply

You must be logged in to post a comment.