Post Pic

Replace full post by excerpts on homepage without editing your theme files

In WordPress, switching from full posts to excerpt is easy if you edit your theme files. But do you know that you could achieve the same result without editing any of your theme file? Just read this recipe to find out.

What you have to do is to paste this code into your functions.php file and let WordPress filters do the work for you.

function my_excerpts($content = false) {
        // If is the home page, an archive, or search results
	if(is_front_page() || is_archive() || is_search()) :
		global $post;
		$content = $post->post_excerpt;

	// If an excerpt is set in the Optional Excerpt box
		if($content) :
			$content = apply_filters('the_excerpt', $content);

	// If no excerpt is set
		else :
			$content = $post->post_content;
			$excerpt_length = 55;
			$words = explode(' ', $content, $excerpt_length + 1);
			if(count($words) > $excerpt_length) :
				array_pop($words);
				array_push($words, '...');
				$content = implode(' ', $words);
			endif;
			$content = '<p>' . $content . '</p>';

		endif;
	endif;

// Make sure to return the content
	return $content;

}

add_filter('the_content', 'my_excerpts');

Thanks to Justin Tadlock for this cool snippet!

2 Responses

Feb 14 2012 19:02

Hi!

Amazing snippet, but I got a problem with it on my site. Do you think you can help?

1. It counts every word, including html-tags. That isnt a big problem in it self, but it creates a problem where the closing-tag often gets placed outside the excerpt and therefore the rest of my site gets bold font if I for example used the b or strong-tag.

Is there any way to automaticly close any open tag before the end of the excerpt?

Sep 05 2012 15:31

Thanks for this. Have been trying to do this without majorly upsetting the current template! Much appreciated!

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox