Ho Ho Ho! It’s December now so you get a Santa-style greeting from me! Today I’ll be showing you a simple trick that I got asked a while back ago in one of the comments, that is: “how can we display excerpt to the more tag (<!–more–>) with WP API V2”?
By default, WP API V2 has the excerpt
field in the posts response, but the auto generated one is often not what we want.
So here are things we’d like to hack around the WP API and get the results we want:
- Get the excerpt with read more link
- Get the excerpt from text before the more tag
- Display content of the shortcodes or oEmbed links in your excerpt
Now let’s get started.
Get the excerpt with read more link
To get the excerpt text to the more tag, we just need to use the built-in WordPress function get_the_content()
. When we insert the more tag into post content, if we use get_the_content()
function to get post content (on any non-single page), we can only get text to the more tag (which will be transformed to a read more link), the left part will be omitted. Let’s add a new my_excerpt
field to the WP API response:
- Line 12: We use the
rest_prepare_post
filter to manipulate the WP API response. Please remember that the best practice is not to modify the default fields, in case the third party apps can’t get the expected data from the API.
Get the excerpt from text before the more tag (without read more link)
What if you just want exactly the excerpt text, but not with the “read more” link? In such case, we’ll need some help from the get_extended()
function:
- Line 7: We use
get_extended()
function to process the$post->post_content
, so we can get an array that separate the content text into three elements: “main”, “extended” and “more_text”. - Line 8: We set
my_excerpt
to$excerpt['main']
because “main” contains text just before the more tag.
Display content of the shortcodes or oEmbed links in your excerpt
The snippet above is not perfect enough because if you have any shortcode or oEmbed link in the excerpt, they won’t be able to be transformed to HTML markup. That’s because in WordPress, we need to process the raw data $post->post_content
with filter the_content
, so all the magical stuff could happen.
Just check out the line 5, apply_filters
here makes everything perfect again.
This is a quite short post and you might have already known these simple tricks! I hope you enjoy the rest days of 2015, and I’m trying to manage to publish another AngularJS tutorial before 2016. Wish I could make it!
If you’re new here, I just want you to know my goal to run this blog is to become the most responsive blogger I’ve ever known. So whenever you have any question regarding my tutorials or not, feel free to leave comments here, email me: yoren [at] 1fix.io or just tweet me: @1fixdotio. I’ll get back to you as soon as I can.
Leave a Reply