When is wp_trim_excerpt() called?

There doesn’t appear to be any reference to wp_trim_excerpt() outside of it’s declaration – I’ve checked both the Trac and Xref – when does it work its magic?

Related posts

Leave a Reply

1 comment

  1. If you’ve already looked in XRef, you’ve seen this comment at the top of the doc block:

    /**
      * Generates an excerpt from the content, if needed.
    

    So it’s not used in core, but is available for you to use if you need it.

    Update

    Let me explain a little of what’s going on:

    excerpt_length and excerpt_more are inside wp_trim_excerpt, and changing them does in fact change the_excerpt and get_the_excerpt. So wp_trim_excerpt has to be doing something somewhere.

    Yes and no. excerpt_length and excerpt_more are being generated by filters. Here’s the inside of the wp_trim_excerpt() function:

    $excerpt_length = apply_filters('excerpt_length', 55);
    $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
    

    By default, $excerpt_length will be set to 55 and $excerpt_more will be set to [...]. However, you can change this in themes and plugins. Let’s say I wanted to sent the length of trimmed excerpts to be 70 characters instead. I’d use the following code:

    function set_new_trim_length( $excerpt_length ) {
        return 70;
    }
    add_filter( 'excerpt_length', 'set_new_trim_length' );
    

    When I call wp_trim_excerpt() later, WordPress will pass that default value of 55 in to my filter function. My filter function will then pass 70 back and wp_trim_excerpt() will use that instead.

    wp_trim_excerpt() doesn’t set or change excerpt_length or excerpt_more when you call it. The function merely uses whatever filters you already have defined for those variables.

    Further Update

    But when you call the_excerpt or get_the_excerpt, they are modified by those filters, so what I want to know is ‘when’ they are modified by those filters.

    This all depends on how you’re building content. There’s a filter applied to get_the_excerpt() that will pass the generated content through the wp_trim_excerpt() function.

    So if you hand-write an excerpt, the hand-written content will be passed through unchanged.

    If you don’t write an excerpt ($post->post_excerpt = ''), the content of the post is passed through wp_trim_excerpt() insted, shortened, and returned.

    For reference, this filter is added on line 147 of /wp-includes/default-filters.php:

    add_filter( 'get_the_excerpt', 'wp_trim_excerpt'  );