Wordpress - Get excerpt using get_the_excerpt outside a loop

I found this question when looking how to do this without the post object.

My additional research turned up this slick technique:

$text = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id));


Since it seems you already have the post object you need the excerpt for, you can just force things to work:

setup_postdata( $post );
$excerpt = get_the_excerpt();

The setup_postdata() function will globalize the $post object and make it available for regular old loop function. When you're inside the loop, you call the_post() and it sets things up for you ... outside of the loop you need to force it manually.


Try this:

Create a new function in functions.php and then call it from wherever.

function get_excerpt_by_id($post_id){
    $the_post = get_post($post_id); //Gets post ID
    $the_excerpt = $the_post->post_content; //Gets post_content to be used as a basis for the excerpt
    $excerpt_length = 35; //Sets excerpt length by word count
    $the_excerpt = strip_tags(strip_shortcodes($the_excerpt)); //Strips tags and images
    $words = explode(' ', $the_excerpt, $excerpt_length + 1);

    if(count($words) > $excerpt_length) :
        array_pop($words);
        array_push($words, '…');
        $the_excerpt = implode(' ', $words);
    endif;

    $the_excerpt = '<p>' . $the_excerpt . '</p>';

    return $the_excerpt;
}

Here's a post describing the code.

Tags:

Loop

Excerpt