Limit content length – WordPress code snippet


Please note the following is only safe to read for fellow geeks!

Anyone looking for a way to limit content length and make custom or multiple excerpt lengths in WordPress might find this very useful.

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 .= ‘<style>’;
$content = strip_tags($content, $allowedtags);
$wordarray = explode(‘ ‘, $content, $content_length + 1);
if(count($wordarray) > $content_length) :
array_push($wordarray, ‘… <a href=”‘. get_permalink() . ‘”>’ . __( ‘Read more &raquo;’ ) . ‘</a>’);
$content = implode(‘ ‘, $wordarray);
$content .= “</p>”;

echo $content;

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.

Happy coding!




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

© Tracey Rickard. If you want to use any of my content please ask me first, you can't use it without permission that's stealing. You can use an excerpt as long as it is linked back to this article.