Blog

How To Get The Excerpt By Post ID

Most WordPress templating functions are available in two formats, one to echo and one to return. These are normally in the form of the_xxx() to display, and get_the_xxx() to return. Some examples of this are:

Aside from differing in returning or displaying the response, the main difference is the context in which these functions can be used. The functions to display need to be used in The Loop, while the functions that return can be used outside the loop by passing in the post ID.

Unfortunately, in true WordPress fashion, there are a few exceptions to this practice, one of which being the functions to get the excerpt. While the_excerpt() will generate an excerpt for the current post in the loop if there is no manual excerpt, get_the_excerpt(), while it can retrieve the excerpt by an ID, it will only get the excerpt if the post has a manually set excerpt. It’s a frustrating deviation from the way these functions generally work.

However there is a solution, using the wp_trim_excerpt() function. This function will either trim down text to the length of a provided excerpt, or generate one based on a specific post’s ID. That doesn’t cater for manually set excerpts, however we can use get_post_field( 'post_excerpt' ) to get that and pass it to wp_trim_excerpt(). Lastly, we can apply the get_the_excerpt filter to allow any plugins attempting to manipulate the excerpt using the standard functions to also have access to the excerpt here too.

<?php
/**
* Get the excerpt of a post by it's ID
*
* @param int $post_id Post ID.
* @return string
*/
function cameronjonesweb_get_excerpt_by_id( $post_id ) {
return apply_filters( 'get_the_excerpt', wp_trim_excerpt( get_post_field( 'post_excerpt', $post_id ), $post_id ), $post_id );
}

Did you find this post useful?

YesNo