I have a code that call get_the_title()
and it works, but get_the_excerpt()
return empty. How can i make it work?
This code is inside a plugin called “WP Facebook Open Graph protocol”. Here’s the part i want to change:
if (is_singular('post')) {
if (has_excerpt($post->ID)) {
echo "t<meta property='og:description' content='".esc_attr(strip_tags(get_the_excerpt($post->ID)))."' />n";
}else{
echo "t<meta property='og:description' content='". [?] ."' />n";
}
}else{
echo "t<meta property='og:description' content='".get_bloginfo('description')."' />n";
}
Here, has_excerpt
always fail, and get_the_excerpt($post->ID)
don’t work anymore (deprecated).
So, how can i display the excerpt there?
ps: I’m using “Advanced Excerpt” plugin as well
I found this question when looking how to do this without the post object.
My additional research turned up this slick technique:
$text = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id));
Since it seems you already have the post object you need the excerpt for, you can just force things to work:
The
setup_postdata()
function will globalize the$post
object and make it available for regular old loop function. When you’re inside the loop, you callthe_post()
and it sets things up for you … outside of the loop you need to force it manually.Try this:
Create a new function in functions.php and then call it from wherever.
Here’s a post describing the code.
Now you can simply use the
get_the_excerpt( $postID )
function.Since: WordPress 4.5.0 introduced the
$post
parameter.got it using
my_excerpt($post->post_content, get_the_excerpt())
and using themy_excerpt()
function from Using wp_trim_excerpt to get the_excerpt() outside the loopIn case you don’t have the post object, here’s a short function like the one from Withers.
This is for when you want to use
get_the_excerpt()
outside the loop:If you’d like to generate the excerpt automatically from the content in one line – you can use
wp_trim_words
function like this: