Replacing WordPress content with an excerpt without editing theme files

I’ve been working away at a new theme for the past couple of weeks. Actually, it’s a theme framework that I’ve been building upon for the last two months or so, slowly trying to put all the bits and pieces together.

I ran into a bit of a hitch though.

Let’s suppose our front page and archives used the WordPress function <?php the_content(); ?> to retrieve all post content. Let’s further suppose we’re want to modify this with a child theme to show excerpts instead of the entire post.

Yes, we could easily just change <?php the_content(); ?> to <?php the_excerpt(); ?>. But, I don’t want to edit the core files at all. I want to be able to upgrade my theme without my modifications being broken.

Solution

WordPress filters.

In my child theme’s functions.php file, I added this bit of PHP:

// Add filter to the_content
	add_filter('the_content', 'my_excerpts');

This tells WP that we want to filter the_content() with our own function.

Here’s what that function looks like:

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;

}

Now, we’ve changed the instances of the_content() that we want to excerpts. This example doesn’t strip the tags of the excerpt like the default WordPress function, but we can easily change that by changing this line:

$content = $post->post_content;

to:

$content = $post->post_content;
$content = strip_shortcodes($content);
$content = str_replace(']]>', ']]&gt;', $content);
$content = strip_tags($content);

There may be a better way to filter the_content(), and I’d love to see what you can come up with if so.

27 responses to “Replacing WordPress content with an excerpt without editing theme files”

  1. Dan Philibin

    This is awesome; I’ve been looking for a solution to this for a long time. However, I really wish the_excerpt() had a link to the full article at the end. Since the ‘…’ can be customized here as well, why not add a link?

  2. Pangeran

    So, that’s how filter works…

    Then, it means we can just modifying a theme with functions.php…
    Thanks for sharing this…

    But if we change the_content with this, how about plug in that add_action to the the_content() ?

    Will it still works?

  3. J Mehmett

    This works like a plugin, Nice trick! That’s why I hate plugins and do like to add everything from theme side.

    So, using filters and actions, child theme will work as a machine… Nice tip, friend.

  4. Justin Tadlock

    Dan
    It’s something I’ve had on my mind for a while too. I just had to sit down and dig through a little of the core WordPress code to see how it works.

    You could definitely add a link to the article with this or tweak it however you want. I wanted to keep the tutorial pretty basic to show how we could use filters a bit.

    Or, we could just filter the_excerpt() and add a link at the end.

    Take a little time to poke around in /wp-includes/post-template.php and /wp-includes/default-filters.php.

    Pangeran
    As far as I know, this shouldn’t mess up the plugins, but I’d have to test a few to confirm that. We’re still returning the $content after we’ve filtered it.

    J Mehmett
    Well, to me themes are plugins. They’re just plugins that deal more with the display of your blog.

    A theme’s functions.php is just a plugin itself too. The more we take advantage of it, the easier it is to keep theme files clean.

    If I can accomplish something easily enough without a plugin, then I’ll usually add it to the theme.

  5. Darren Hoyt

    That’s a cool use of filters, Justin. These days I usually just include a file called ‘loop.php’ with my themes which uses a bunch of conditionals to determine content vs. excerpt depending on the page you’re on. I’m liking the idea of using filters now, though.

  6. Justin Tadlock

    Darren
    I was torn between using conditional tags within the theme files or filtering it. I’ve tried the loop.php approach before and it works for some projects.

    Since I’m building this a bit upon a theme framework, which I’ll be working exclusively with for quite some time, I figured I’d use a filter, which would allow me to work with multiple types of layouts without changing the core theme files.

    My main goal recently has been to make default theme files as bland and unexciting as possible, which makes it easier for the user in the long run.

  7. Gustavo Ayres

    Hi Justin,

    This was exactly what I was looking for. I was trying to do something like that.
    The only problem I had is tha I use a plugin [can't remember the name] that I can add some BBCODE-like on my text and it makes a adsense banner appear. I put something like:

    [ad#banner-post]

    And it shows the banner.

    Using the code you put here, it doesn’t work anymore. Do you have any idea why it stopped work?

    Thanks in advance

  8. J Mehmett

    I was thinking about adding some extra code in your above code, so I could make the links in the post appear in the the_excerpt(); too as they appear in the the_content();. Because, the_excerpt(); doesn’t show links in the post by default. I’ll give it a try.

    Of course the more we use functions.php the less we need a plugin.

  9. edoluz

    Thanks again Justin!! Great work!!!

  10. Link Love and Updates September 14 | Unlock The Online World

    [...] 1. Nihar-How to group chat with GTalk 2. Tara- Social Network Rundown 3. WPCandy- Easier Theme Development With Sample Posts 4. Pearsonified-How You Can Use WordPress Functions to Run a Smarter Blog 5. Justin Tadlock-Replacing WordPress content with an excerpt without editing theme files [...]

  11. impNERD

    This would be much better served as a plugin. You could easily set what pages this should effect as well.

  12. Nihar

    Great tip. I will try to implement this.

    Thanks..

  13. baldo

    Sorry guys but Im not a php guy. I follow the abouve procedure and put the code “// Add filter…” and “function my_excerpts…” to mu function.php under my present theme. But could not get it to work.

    The article post still displays the whole article. Need help.

  14. baldo

    oh by the way, does it also filters even old posts? I wanted to reduce ALL articles on my blogs to show only a number of characters. Thanks

  15. Justin Tadlock

    impNERD
    When you’re working with the concept of child themes, this is much better within the theme. Themes should control how your content is output anyway.

    Nihar
    No problem. ;)

    baldo
    This is something that’s really for someone that’s comfortable using PHP, especially in the context of a child theme, and only when the situation warrants it.

    It may be better to just use the_excerpt() instead of the_content() within your theme files.

    The code above definitely works. I’m using it at Theme Hybrid.

  16. Lucía

    Thanks!! This helped a lot, you made my day :D

  17. Sparrow

    Hey Justin,

    This looks like the perfect solution to what I want to do. But you will have to forgive me as I am a newbie to the WordPress world. That being said, I am a little frustrated that WordPress’s own documentation and then here doesn’t say *where* to add this code or in what files..? Did I miss something?? As I said I am new, but it is like everybody assume that you know where these functions are!

    If you could advise I would quite grateful for the time it will save me sifting through files.

    Many thanks in advance!

  18. Justin Tadlock

    Actually, it does say where to add this code in the post. There’s this line that reads:

    In my child theme’s functions.php file, I added this bit of PHP:

    Of course, you could simply add this in your theme’s functions.php file as well if you’re not using parent/child themes.

  19. Wordpress Blog Services - Most Wanted WordPress Hacks: 11 New Requests (2)

    [...] Justintadlock has the solution: WordPress filters [...]

  20. 11个新WordPress技巧 | Housne Space

    [...] Justintadlock有解决此问题的方法:WordPress filters [...]

  21. Barrett Golding

    great script, Justin.
    i added a linked-to-post ellipsis ($postlink) at the end of the excerpt:

    Deleted by admin. Please use character entities when posting code.

    to get it w/in the auto-added tags of the “optional excerpt”,
    i added the link to your script here::
    $content = apply_filters('the_excerpt', $content . $postlink);

    then i also added it you your “if no excerpt” script here:
    $content = '' . $content . $postlink . '';

    not sure if that’s the best way to do job, but it does work in both cases:
    http://hearingvoices.com/news/2008/

  22. Barrett Golding

    oh, forgot, i also removed your ellipsis here:
    array_push($words, '');

  23. Jauhari

    Hi Justin, Is it possible on the excerpt remove the Image only? and keep the other thing on the content just like the original?

  24. 11个备用的WordPress编程技巧 - 菠菜博

    [...] Justintadlock有解决此问题的方法:WordPress filters [...]

  25. 11个新而实用的 WordPress 技巧【下篇】 at 时间与空间的屋子

    [...] 中加入以下代码,告诉WP您想将 the_content() 过滤成自己定义的函数(可参考详细教程): // Add filter to the_content add_filter(’the_content’, [...]

  26. Brian Mecham

    This doesn’t seem to work when your front page is a static page and not the blog page… I assume I’ll need to replace is_front_page with something else? but what?

  27. Brian Mecham

    I guess I’ll reply to my own question since I figured it out… instead of is_front_page I put is_home - that’s in this part of the code in case you are wondering:
    // If is the home page, an archive, or search results
    if(is_home() || is_archive() || is_search()) :
    global $post;
    $content = $post->post_excerpt;

    This makes blog post excerpts when front page is static and blog page is a different page.

Leave a Reply

By submitting a comment here you grant this site a perpetual license to reproduce your words and name/web site in attribution.

WordPress-o-Sphere