Learning never exhausts the mind
Home >  Web Design > WordPress > WordPress Get the Excerpt Outside the Loop

Last Updated on by

The WordPress template tag the_excerpt and get_the_excerpt are great for showing a short summary of a post, in fact, this paragraph is the excerpt for this post.

Unfortunately, you cannot use get_the_excerpt outside "the loop". This is a similar function that can be used anywhere in your theme or template.

This snippet can even be used to display the excerpt for any post anywhere on any page. Just pass in the post ID of the post to show the excerpt for.

function get_the_excerpt_here($post_id)
{
  global $wpdb;
  $query = "SELECT post_excerpt FROM $wpdb->posts WHERE ID = $post_id LIMIT 1";
  $result = $wpdb->get_results($query, ARRAY_A);
  return $result[0]['post_excerpt'];
}
11 thoughts on “WordPress Get the Excerpt Outside the Loop
  • 16th January 2014 at 12:00 am

    it does not work in 3.8
    any help plz....

    Reply
  • 30th September 2012 at 12:00 am

    can u plz explain where do i have to put this code?

    Reply
    • Tim Trott
      29th November 2012 at 12:00 am

      This code would be used in a template anywhere outside of "the loop", for example the header, footer or sidebars.

      Reply
  • Michael Robinson
    17th March 2012 at 12:00 am

    Thanks for posting this. Seems obvious really, one would assume that for something so obviously useful, WP would provide a function for it!

    Reply
  • Rob
    30th November 2011 at 12:00 am

    Brilliant, thank you!

    Reply
  • Laurize
    17th August 2011 at 12:00 am

    How do I pass the post ID? thanks

    Reply
  • 6th August 2011 at 12:00 am

    Perfect! Just what I was looking for

    Cheers
    D

    Reply
  • Gwyneth Llewelyn
    5th July 2011 at 12:00 am

    Hmm. What if I need an automatically generated excerpt? It won't be stored on the database.

    Reply
  • estevan
    11th August 2010 at 12:00 am

    Is there any way to have this pull an excerpt of the most recent post instead of specifying an ID?

    Reply
    • vaseem
      2nd March 2011 at 12:00 am

      @estevan, Hello dear, you can easily get the latest post excerpt using the following query

      SELECT post_excerpt FROM $wpdb->posts where `post_status`='publish' && post_excerpt!='' && post_password='' && (post_type!='post' OR post_type!='page') ORDER BY `ID` DESC LIMIT 1

      Have fun and Bye

      Reply
  • 18th October 2009 at 12:00 am

    Thanks so much for this, I've been searching for a solution to this for some time.

    Reply

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.