You may think that a function like “the_excerpt()” on WordPress is something of simple. Actually it is not and I discovered it while trying to manipulate it.

The function “the_excerpt()” is widely used in themes to create a brief presentation of a post. The function extract few words from the post, removing not useful stuff (like images). Following the full path from the call to the result is pretty interesting,

  1. the_excerpt() calls get_the_excerpt() and applies the filter “the_excerpt” on its returned value and echo the filtered text
  2. get_the_excerpt() obtains the current post with get_post() (which is a rater complex function) and then applies the filter “get_the_excerpt” on the post excerpt field (the field you can compile when writing a post but which is usually left blank) and returns the result
  3. WordPress has a function attached to the filter “get_the_excerpt” which is wp_trim_excerpt()
  4. wp_trim_excerpt() checks if the passed text is blank (usually it is since few people compile the excerpt field of a post) and if it’s the case, calls get_the_content() which executes all the shortcodes (this can be the dangerous part, see later)
  5. the value returned by get_the_content(), other than some filtering, it’s passed through the  wp_trim_words() function, which build the real excerpt
  6. the wp_trim_words() removes all tags which are not good for an excerpt and does it calling the wp_strip_all_tags()
  7. the value is returned back (even if some other filters can be applied if themes or plugins define them)

As you can see, the_excerpt() uses the_content(): that means you cannot (without some form of protection), call the_excerpt() inside a function binded to the “the_content” filter. Of course I know it because I met it… (produces an infinite recursion).

Why someone should call the_excerpt() from the the_content()? It could be useful when a theme uses the_content() on archive pages where you want to have the excerpt (and the theme does not supply an option for that – like the WordPress standard themes).

A solution is to directly use the wp_trim_words() from your “the_content” filter.

Similar Posts

Leave a Reply