Troy Chaplin

Design & Development

Posted in the Blog

Variable Post Excerpt Lengths Based on Title Character Count

If you are looking to create a post landing page layout that flows across multiple columns while maintaining a consistent height to each post coming through from the loop, then the following piece of code will do just that. It will allow you to set the number of characters output on the excerpt based on the title character count.

	$excerpt = strip_tags(get_the_excerpt());
	$title_len = strlen($post->post_title); //get length of title
	if($title_len <= 30){
		$limit=270; //calc space remaining for excerpt
	else if ($title_len <= 60){
		$limit=230; //calc space remaining for excerpt
	else if($title_len <= 75){
	$summary = substr($excerpt, 0, strrpos(substr($excerpt, 0, $limit), ' ')) . '...';
	echo $summary;
<a href="<?php the_permalink(); ?>" title="Read Full Post: <?php the_title(); ?>">More&nbsp;&raquo;</a>

The way this works is rather simple. The $title_len represents the length of the post title, while the $limit represents the excerpt length limit. In the first if statement, the title_len is less than 30 characters, then the excerpt will output 270 characters.

The next series of else if statement function in the same way, reducing the size of the excerpt as the title character counts increases. This example only displays 3 possible sizes, but add more else if’s if required.

The second portion of the code will create a summary by stripping the post and apply the conditional statement values, which will then be output onto the page wrapped in p tags. The first line of the summary also end with three periods, this can be changed to whatever you wish to output to end the excerpt text.

The read more link is the last line of the code, simply change the READ MORE LINK portion of the code to set the text for viewing the full post.

Post a Comment

Your email is never published nor shared. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>