Post Pic

WordPress: Improved the_excerpt() function

The the_excerpt() function is useful and very popular among theme developers, but it’s far from being perfect. Today’s recipe showcase an improved the_excerpt() function, which display an excerpt which is not longer than a predetermined length and doesn’t cut off in mid-sentence.

The first thing to do is to create the function. Open your functions.php file and paste the code below in it.

// Variable & intelligent excerpt length.
function print_excerpt($length) { // Max excerpt length. Length is set in characters
	global $post;
	$text = $post->post_excerpt;
	if ( '' == $text ) {
		$text = get_the_content('');
		$text = apply_filters('the_content', $text);
		$text = str_replace(']]>', ']]>', $text);
	}
	$text = strip_shortcodes($text); // optional, recommended
	$text = strip_tags($text); // use ' $text = strip_tags($text,'<p><a>'); ' if you want to keep some tags

	$text = substr($text,0,$length);
	$excerpt = reverse_strrchr($text, '.', 1);
	if( $excerpt ) {
		echo apply_filters('the_excerpt',$excerpt);
	} else {
		echo apply_filters('the_excerpt',$text);
	}
}

// Returns the portion of haystack which goes until the last occurrence of needle
function reverse_strrchr($haystack, $needle, $trail) {
    return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}

Once done, you can use the print_excerpt() function in your theme files, as shown below:

<?php print_excerpt(50); ?>

Thanks to Sebastian for the function!

Related Posts

No related posts.

6 Responses

Jan 12 2012 20:59

excellent! exactly what i needed at a current project.
thanks for the code!

regards,
andi

Apr 30 2012 17:46

Thanks.. it’s works

May 19 2012 20:58

Thanks for this short tutorial, but how can we add the link to the page. Increasing the number of characters doesn’t work. I don’t want it saying ‘Read More’ or similar but making the title as the link would make more sense.

Dec 30 2012 04:16

Thank you! Good job!

Jan 27 2013 18:43

Hello, for one of my sites I’m using truncate_post function and it’s a standard php function for truncating the post. However, when viewing the page source, it leaves to much empty space before truncate the post. I’m saying TOO MUCH. Now I’m going to try the excerpt funtion, so let see if it will be better.

Apr 21 2013 02:00

Thanks!

Maybe a little better like $excerpt = reverse_strrchr($text, ‘. ‘, 1); ?

Space after period would stop ‘www.somesite.com.’ from cutting off in the middle.

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox