Wordpress - GET the excerpt by ID

Hi @Robin I. Knight:

I view get_the_excerpt() as a function with legacy design. As WordPress usage has grown there are many newer use-cases where it doesn't fit but where the newer functions for getting different data do. One example is the now frequent use of an $args array of function options.

But it's easy to fix for your needs. Here's an alternative function you can use which you can put anywhere in your theme's functions.php file:

function robins_get_the_excerpt($post_id) {
  global $post;  
  $save_post = $post;
  $post = get_post($post_id);
  $output = get_the_excerpt();
  $post = $save_post;
  return $output;
}

I've not tested it but am pretty sure I got it right. If this doesn't meet your needs please elaborate and maybe I can make other suggestions.


The mechanics of excerpt are extremely confusing. It is not precise answer to your question but in general if you need to make template tags, specific to Loop, work with array returned by get_posts() you can emulate Loop like this:

$stories = get_posts(); 

foreach ($stories as $post) {

    setup_postdata($post);

    // stuff
}
wp_reset_postdata();

There is a new function since 3.3.0: wp_trim_words

I'm using it outside the loop as follows:

 <?php if ( $post_id ) {
 $post = get_post( $post_id );
 if ( $post ) { ?>
     <h2><?php echo $post->post_title; ?></h2>
     <p><em><?php echo wp_trim_words( $post->post_content ); ?></em></p>
     <p><strong>This article can only be read by subscribers.</strong></p>
 <?php } } ?>

This is not to be confused with wp_trim_excerpt that apparently only works within the loop, since it calls the_content() internally.

Tags:

Posts

Excerpt