How do I filter get_the_excerpt() but keep all of its functionality intact?

I have a custom meta field that I want to display as my excerpt. I use a filter that does this for me:

add_filter( 'get_the_excerpt', function($output){
  $output=get_post_meta(get_the_ID(), 'my_meta_field', true);
  return $output;
});

Now whenever I use get_the_excerpt() or the_excerpt() inside of the loop I get the content of my_meta_field.

But since WP 4.5.0 get_the_excerpt() accepts a Post ID or WP_Post object as parameter. I would like to keep this functionality intact while using my filter.

So imagine I want to use get_the_excerpt() outside of the loop. When I call get_the_excerpt(1234) (1234 being the ID of a post) I get the wrong excerpt back because the get_the_ID() in my filter grabs whatever global $post has to offer at that moment.

What is the most elegant / efficient way to solve this? Can I somehow use the ID I am passing to get_the_excerpt inside my filter? Or do I need to create a mini loop and set global $post to get_post(1234)?

2 Answers
2

In spite of what the Codex says, since WP 4.5, where the addition of the post argument to the function get_the_excerpt was added, this filter takes two arguments. The second argument is the post object whose excerpt you are manipulating.

So the function still works in the loop without an explicit post, we make the second argument optional.

add_filter( 'get_the_excerpt', 'wpse_242462_excerpt_filter' );

function wpse_242462_excerpt_filter( $excerpt, $post = null ){

      if ( $post ) {
        $ID = $post->ID;
      } else {
        $ID = get_the_ID();
      }

      $excerpt = get_post_meta( $ID, 'wpse_242462_meta_field', true);

      return $excerpt;
});

Hopefully it goes without saying that you need to substitute whatever meta key you are already using.

Leave a Comment