Support » Developing with WordPress » Blog Post Excerpt in REST API call

  • I’m trying to limit blog post description when getting from REST API for widget on my non WP website. I tried different plugins for WP, I tried to set filter:

    function custom_excerpt_length( $length ) {
        return 100;
    }
    add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

    Nothing works. How can I make it?

    • This topic was modified 1 year, 9 months ago by  cutoffurmind.
    • This topic was modified 1 year, 9 months ago by  Steve Stern.
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    The complete REST response is filtered through “rest_prepare_post”. You can alter the response here in any way you want. Extract the excerpt from the passed REST response, run it through wp_trim_words(), then place the trimmed version back into the response, replacing the original excerpt element.

    could you show where should I do that? And also does wp_trim_words() consider HTML tags? Because when I got post I have it with tags like <p>

    • This reply was modified 1 year, 9 months ago by  cutoffurmind.
    Moderator bcworkz

    (@bcworkz)

    Well, you can add the filter and declare your callback function any where that’s part of the WP load process. For custom code you should either create a child theme or your own plugin to contain such code. You could place the code in the current theme’s functions.php, though it’ll be overwritten during an update.

    I’ve not used this filter, so I’m not sure exactly what’s passed, I’m assuming the complete JSON response. So you need to decode it with json_decode(). Dump out the resulting array to figure out the proper addressing required to extract the value you want. It might be something like $response->excerpt->rendered, but you should verify for yourself. Trim it, then update the array, which you then run through json_encode() before returning the response.

    wp_trim_words() does not count HTML tags. In fact, it strips them out entirely. If you wish to retain tags but not count them as words, I think you may need to concoct your own algorithm, though there’s probably examples available with a bit of searching.

    Note the filter suggested only works for “post” post types. For other post types, replace “post” with whatever post type you want to adjust.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Blog Post Excerpt in REST API call’ is closed to new replies.