Trouble trunctaing the_excerpt() in wordpress

If you are like me, you’ll find that the_excerpt() leaves a lot to be desired. I don’t like you having to add more tags to your content or else everything is displayed. This over run of content messes with the theme I designed. I decided a few themes ago to get rid of the_excerpt() and modify the way I use the_content().

I built this truncation class. I add it to the function.php file and call it instead of calling the_excerpt().

class truncate{
/* Public function for truncating content
* Requires an string and a length
*
* Structure:
* $truncateString = ‘text ro truncate’
*
* Example:
* $truncateString = truncate::doTruncate($_POST['truncate'], 100);
*
* Returns:
* return truncated string;
*/

public static function doTruncate($truncateString, $limit, $break=”.”, $pad=”…”) {

// return with no change if string is shorter than $limit
if(strlen($truncateString) <= $limit) return $truncateString;

// is $break present between $limit and the end of the string?
if(false !== ($breakpoint = strpos($truncateString, $break, $limit))) {

if($breakpoint < strlen($truncateString) – 1) {

$truncateString = substr($truncateString, 0, $breakpoint) . $pad;

}

}
return $truncateString;

}

}

With this class I am able to use:

<?php $permalink = ‘ <a href=”‘.get_permalink().’”>Read More…</a>’; ?>
<?php $truncateContent = truncate::doTruncate(strip_tags(get_the_content(), ”), 300, ‘.’, $permalink); ?>
<p><?php echo $truncateContent; ?></p>

I often read about people wanting to change the More links. Guess what? With this class you simply pass a replacement value for $pad=”…”. Such as the $permalink value I am sending in the example above. I wanted my links to say Read More… If you want it to say something else simple change the text in the $permalink value to anything you want.

If you have been looking for a better way to truncate you WordPress post or you want to change your More links then you have found the solution. Feel free to use the code above, but if possible please add a link back to this article.

Thanks.


Tags: , , , , ,






Powered by Wordpress, Power Theme designed by Wordpress Power Themes.