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!

1 Answer
1

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;

Leave a Reply

Your email address will not be published. Required fields are marked *