user2929830
user2929830

Reputation:

Get raw HTML output from WordPress REST API

I'm using the WordPress REST API to get the HTML content of my WordPress page in an external application. I'm calling this mysite/wp-json/wp/v2/pages/10 and it returns:

"content": {
  "rendered": "[vc_column_text]Hello World[/vc_column_text]"
}

Is there any way to return the code in it's final HTML output and without the [vc_] shortcodes, eg: <p>Hello World</p>

The shortcodes are coming from the Visual Composer page builder plugin.

Upvotes: 8

Views: 12143

Answers (2)

muka.gergely
muka.gergely

Reputation: 8329

Found and answer here: https://github.com/CompassHB/web/issues/67#issuecomment-245857301

The example below is taken from the link above:

/**
 * Modify REST API content for pages to force
 * shortcodes to render since Visual Composer does not
 * do this
 */
add_action( 'rest_api_init', function ()
{
   register_rest_field(
          'page',
          'content',
          array(
                 'get_callback'    => 'compasshb_do_shortcodes',
                 'update_callback' => null,
                 'schema'          => null,
          )
       );
});

function compasshb_do_shortcodes( $object, $field_name, $request )
{
   WPBMap::addAllMappedShortcodes(); // This does all the work

   global $post;
   $post = get_post ($object['id']);
   $output['rendered'] = apply_filters( 'the_content', $post->post_content );

   // EDIT: add custom CSS to $output:
   $output[ 'yb_wpb_post_custom_css' ] = get_post_meta( $object[ 'id' ], '_wpb_post_custom_css', true);

   return $output;
}

EDIT

A question arose in a comment: how to get the custom CSS set for a page (post, etc.)? I modified the sample code in a way that it adds the custom CSS to the REST API response. You'll find the CSS in content/yb_wpb_post_custom_css.

The other way is to add another field to the REST API response that contains this CSS. The key is that the custom CSS set for a page/post/etc. has a meta key _wpb_post_custom_css.

Upvotes: 3

Nachiket Namjoshi
Nachiket Namjoshi

Reputation: 11

About 2 years late to the party, however, the following worked for me:

$output['rendered'] = apply_filters( 'the_content', get_the_content() );

Just in case if anyone was wondering.

Upvotes: 1

Related Questions