Web Design that taps into the haromny and vision of your dreams.

Wordpress Get the Excerpt Outside the Loop

Sometimes template tags can only be used in the loop

Written By on in PHP

92 words, estimated reading time 1 minutes.

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'];
}

Last updated on: Wednesday 21st June 2017

 

Comments
Shahin

Shahin

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

Reply to Shahin
Eli dan

Eli dan

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

Reply to Eli dan
Tim Trott

Tim Trott

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

Reply to Tim Trott
Michael Robinson

Michael Robinson

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

Reply to Michael Robinson
Rob

Rob

Brilliant, thank you!

Reply to Rob
Laurize

Laurize

How do I pass the post ID? thanks

Reply to Laurize
david

david

Perfect! Just what I was looking for

Cheers
D

Reply to david
Gwyneth Llewelyn

Gwyneth Llewelyn

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

Reply to Gwyneth Llewelyn
estevan

estevan

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

Reply to estevan
vaseem

vaseem

@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 to vaseem
Phil Dodd

Phil Dodd

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

Reply to Phil Dodd

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me