November 15th, 2009

WordPress Custom Content Length (Code Snippet)

While I was coding this website, I was looking around for a piece of WordPress code allows you to display an excerpt of a certain length.

Frankly, I really feel that a custom content length should be built into the WordPress core.

Anyway, there are plugins available but just didn’t want to add another one to the installation if I can help it… so I decided to add a simple function instead…

For those interested:

function limit_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_pop($wordarray);
		array_push($wordarray, '...');
		$content = implode(' ', $wordarray);
		$content .= "</p>";
	endif;

	echo $content;
}

Just copy the above code into your functions.php file.

Usage:

limit_content( $length,  $allow-tags, $tags-to-allow )

Example:

limit_content('300',  false, '<p><a>');

Parameters:

$length
(integer) Number of characters desired.

Default: 250

$allow-tags
(string) (optional) Allow any formatting?

Default: true

$tags-to-allow
(string) (optional) If $allow-tags is set to false, you can use this parameter to selectively allow certain formatting tags.

Default:  ‘ ‘

$content .= "</p>";

Shortlinks

Leave a Comment

Or Comment using....

Facebook Connect

Skip the hassle of typing in the required fields! Link Fusedthought Studio with your Google, Facebook or other connect enabled accounts.

Top