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)
?