从WordPress REST API获取原始HTML输出


Get raw HTML output from WordPress REST API

我正在使用WordPress REST API在外部应用程序中获取WordPress页面的HTML内容。我称之为mysite/wp-json/wp/v2/pages/10,它返回:

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

有没有办法在最终的HTML输出中返回代码,并且没有[vc_]短代码,例如:<p>Hello World</p>

短代码来自Visual Composer页面构建器插件。

在这里

找到并回答:https://github.com/CompassHB/web/issues/67#issuecomment-245857301

下面的示例取自上面的链接:

/**
 * 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;
}

编辑

评论中出现了一个问题:如何为页面(帖子等(设置自定义 CSS?我修改了示例代码,将自定义 CSS 添加到 REST API 响应中。您会在 content/yb_wpb_post_custom_css 中找到 CSS。

另一种方法是将另一个字段添加到包含此 CSS 的 REST API 响应中。关键是页面/帖子/等的自定义 CSS 集具有元键_wpb_post_custom_css

然而,晚了大约 2 年,以下对我有用:

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

以防万一有人想知道。