Getting a WP Post Excerpt Outside The Loop – Updated

Earlier, I posted a link to an excellent post which saved me the job of figuring out how to grab a WP post excerpt for use outside The Loop.

However, it wasn’t absolutely perfect for my needs, so here is my updated version – hopefully it comes in useful for somebody else:

function fr_excerpt_by_id($post_id, $excerpt_length = 35, $line_breaks = TRUE){
$the_post = get_post($post_id); //Gets post ID
$the_excerpt = $the_post->post_excerpt ? $the_post->post_excerpt : $the_post->post_content; //Gets post_excerpt or post_content to be used as a basis for the excerpt
$the_excerpt = apply_filters('the_excerpt', $the_excerpt);
$the_excerpt = $line_breaks ? strip_tags(strip_shortcodes($the_excerpt), '<p><br>') : strip_tags(strip_shortcodes($the_excerpt)); //Strips tags and images
$words = explode(' ', $the_excerpt, $excerpt_length + 1);
if(count($words) > $excerpt_length) :
  array_push($words, '…');
  $the_excerpt = implode(' ', $words);
  $the_excerpt = $line_breaks ? $the_excerpt . '</p>' : $the_excerpt;
$the_excerpt = trim($the_excerpt);
return $the_excerpt;

The differences are based primarily on my use case. I’m attempting to use this to auto-generate <meta> tag content for certain post types to be used in Open Graph Tags for Facebook and Twitter Card markup. Just make it reusable elsewhere, I’ve added the ability to keep paragraphs or breaks as dictated in the Post Excerpt/Content; and am passing the Excerpt Length as a variable, rather than needing to set and forget in the actual function.

My primary use case is in code used in the <head> section of my site – it could be hardcoded in your header.php file or, preferably, passed in via a function. For example:

<?php $my_excerpt = fr_excerpt_by_id($post_id, 40, FALSE);

// $post_id is the id of the desired post. We want an excerpt of up to 40 words, with <p> and <br /> tags stripped.

echo '<meta property="og:description" content="' . $my_excerpt . '" />';
// example usage for an Open Graph description tag

Alternatively, for use in a sidebar or similar:

<div class="widget">
<?php echo fr_excerpt_by_id($post_id); ?>

$post_id is the id of the desired post. Display a default 35 word excerpt with surrounding <p> tags, and line breaks (if applicable)

Those are a couple of limited use cases, but should be enough to help figure out other possible applications.

Getting a WP Post Excerpt Outside The Loop

Nicely done, Mr Davis – saved me a job!