Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress REST API: How to get the "word-only" content in WP REST API JSON File?

I am using WP REST API to retrieve data from my website, for example, from this http: http://localhost:8888/wordpress/wp-json/wp/v2/posts/42 I can the the info of the post 42, but inside the content section, it shows like this

enter image description here

the actual post is in the format:

this is a test blog +[image]+this is a test blog+[image]

all I want from the content section is just the word, not the image's information, what can I do to achieve this?

and what kind of format WP REST API returned for this content section? I read from the website, it said it's "object". I am new to WP.

like image 705
Leo Guo Avatar asked Aug 23 '16 09:08

Leo Guo


1 Answers

You need to hook in to rest_api_init and modify how you need the content to be.

add_action( 'rest_api_init', function ()
{
   register_rest_field(
          'post',
          'content',
          array(
                 'get_callback'    => 'do_raw_shortcodes',
                 'update_callback' => null,
                 'schema'          => null,
          )
       );
});

function do_raw_shortcodes( $object, $field_name, $request )
{
   global $post;
   $post = get_post ($object['id']);
   // This is what we currently have...
   $output['rendered'] = apply_filters( 'the_content',  $post->post_content);
   // This includes the shortcodes
   $output['_raw'] = $post->post_content;
   // Add something custom
   $output['foo'] = 'bar';
   return $output;
}

You should then see the extra data in the JSON.

like image 50
Kosso Avatar answered Oct 21 '22 07:10

Kosso