WordPress: how to replace the output of the the_content() function with the post's excerpt

WordPress: how to replace the output of the the_content() function with the post's excerpt

A simple way to filter out the output of the WordPress the_content() function and replace it with the post's excerpt.

When you change your mind, sometimes it's difficult to restore the original design of your WordPress theme without breaking something. Suppose that you've been using the the_content() function in your theme files for quite a while until you realize that the amount of content shown on the home, tag and category pages is actually too long. So you decide to use the the_excerpt() function but you should manually modify all your files. Fortunately, there's a solution.

You can create the following filter:


function replace_content_with_excerpt($content) {
	global $post;
	$id = $post->ID;
	
	if(!is_single($id) && !is_page($id)) {
		$content = get_the_excerpt($id);
		$more = '<p><a href="' . get_permalink($id) . '" class="more-link">Continue Reading</a></p>';
		
		return $content . $more;
	}
	
	return $content;
}

add_filter('the_content', 'replace_content_with_excerpt');

The above function replaces the output of the the_content() function with the contents of the post's excerpt. Of course this replacement takes place only when it's actually needed.