Limit content length – WordPress code snippet

The Brilliant WordPress

This is a post for other WordPress developers.

Any WordPress developer looking for a way to limit content length and make custom or multiple excerpt lengths in WordPress might find this very useful.  When I added this a few years ago it was something of a challenge to resolve, hence I hope it helps others.

You can of course get all of your questions answered via the WordPress support forum. This is the right place for you to learn, share and troubleshoot any issues you might have.

The code

The $allowtags function is very useful.

This goes in the functions file, these are global settings but you can vary these by what you put in your page template:

// Content limiter with tag selection
function limited_content($content_length = 250, $allowtags = true, $allowedtags = '') {
global $post;
$content = $post->post_content;
$content = apply_filters('the_content', $content);
if (!$allowtags){
$allowedtags .= '
$content = strip_tags($content, $allowedtags);
}
$wordarray = explode(' ', $content, $content_length + 1);
if(count($wordarray) > $content_length) :
array_pop($wordarray);
array_push($wordarray, '... ' . __( 'Read more »' ) . '');
$content = implode(' ', $wordarray);
$content .= "</p>";
endif;
echo $content;
}

Then this goes in the page template as appropriate:

php limited_content(120); ?>

Will output 120 words of the post and all of the tags that go with it, e.g. <img>, <a> etc.

php limited_content(25, false); ?>

Will output 25 words of the post with no tags, so in other words a custom excerpt length.

Get Involved with WordPress

Whether you’re a budding developer, a pixel-perfect designer, or just like helping out, theyr’re always looking for people to help make WordPress even better.

There are many different ways you can get involved and give back to WordPress.  A great place to start is by answering questions in the support forum.  As WordPress say, everyone knows the answer to something. You can find out more at Make WordPress.

More WordPress Developer Reading

Share on FacebookTweet about this on TwitterPin on PinterestShare on LinkedInShare on Google+Email this to someone