As all of us know that excerpts play a very important role on our WordPress sites front page in case we are showing a list of posts with a short summary. In WordPress, either we can enter a manual excerpt on the edit post panel or if this field is empty, WordPress automatically considers the first 55 words of the post content as the post’s except.
[recommended]You may also like to read: Show Posts From Selected Categories On WordPress Blog Homepage[/recommended]
While in the WordPress loop we can pull the excerpt using the get_the_excerpt() template tag, we cannot using this template tag to get the excerpt outside the WordPress loop. So what if we know the post ID and we need to get the post’s excerpt using the post’s ID, somewhere in our WordPress template file. I just got such a need when I was developing one of my latest WordPress plugin.
[ad id=’15’ style=’margin:10px 0;’]
I use the below function to get the excerpt in such cases:-
$query = ‘SELECT post_excerpt FROM ‘. $wpdb->posts .’ WHERE ID = ‘. $post_id .’ LIMIT 1′;
$result = $wpdb->get_results($query, ARRAY_A);
Just use the function with the ID of the post as the argument and it will return you the excerpt for that particular post.
Example call: Say if the post ID for which you need the excerpt is 524, you can call the function as follows:-
[php]$excerpt = get_excerpt_outside_loop(‘524’);[/php]
And thus you get the excerpt outside the WordPress loop easily.