3

I am modifying the output of a plugin using a filter, and the $post variable is available to me, so I can display the post content like so:

<h3><?php echo $post->post_title; ?></h3>
<?php echo apply_filters( 'the_excerpt', $post->post_excerpt ); ?>

However, the above only displays the excerpt if content has been entered into the excerpt field. It doesn't show a truncated version of the content like it would if you were able to use "the_excerpt" or "get_the_excerpt". I've also tried:

<?php echo apply_filters( 'the_excerpt', $post->post_content ); ?>

But that just gets the full content of the post.

And I tried this:

<?php echo apply_filters('the_excerpt', get_post_field('post_excerpt', $post-ID)); ?>

But that returns nothing.

Is there a way to get the excerpt from the full content from $post when I can't use the_excerpt or get_the_excerpt?

Thank you!

  • By default, WordPress should be taking the first 55 words of the_content to serve as the_excerpt if none is explicitly defined. – Cedon May 26 '17 at 1:07
  • Correct. But I can't use the_content or the_excerpt in this case. I have to use $post->post_content or $post->post_excerpt. – LBF May 26 '17 at 1:10
4

When in the loop, this will produce excerpt from $post->post_content directly:

<?php echo wp_trim_excerpt(); ?>

Read more HERE.

Alternative Solution:

If you are not in the loop, then, you may use similar implementation as done in the wp_trim_excerpt function:

$text = strip_shortcodes( $post->post_content );
$text = apply_filters( 'the_content', $text );
$text = str_replace(']]>', ']]&gt;', $text);
$excerpt_length = apply_filters( 'excerpt_length', 55 );
$excerpt_more = apply_filters( 'excerpt_more', ' ' . '[&hellip;]' );
$text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
echo $text;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.