Wordpress - Using wp_trim_excerpt to get the_excerpt() outside the loop

Since WP 3.3.0, wp_trim_words() is helpful if you're able to get the content that you want to generate an excerpt for. Hope that's helpful to someone and it saves creating your own word counting function.

http://codex.wordpress.org/Function_Reference/wp_trim_words


wp_trim_excerpt() has a little curious mechanics - if anything is passed to it then it does nothing.

Here is basic logic behind it:

  • get_the_excerpt() checks for manual excerpt;
  • wp_trim_excerpt() chimes in if there is no manual excerpt and makes one from content or teaser.

Both are tightly tied to global variables and so Loop.

Outside the Loop you are better of taking code out of wp_trim_excerpt() and writing your own trim function.


Update:

Here is a derivative of wp_trim_excerpt() which I used. Works perfectly. Derived from Wordpress version 3.0.4

function my_excerpt($text, $excerpt)
{
    if ($excerpt) return $excerpt;

    $text = strip_shortcodes( $text );

    $text = apply_filters('the_content', $text);
    $text = str_replace(']]>', ']]>', $text);
    $text = strip_tags($text);
    $excerpt_length = apply_filters('excerpt_length', 55);
    $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
    $words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
    if ( count($words) > $excerpt_length ) {
            array_pop($words);
            $text = implode(' ', $words);
            $text = $text . $excerpt_more;
    } else {
            $text = implode(' ', $words);
    }

    return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}

Tags:

Excerpt