【问题标题】:Get raw HTML output from WordPress REST API从 WordPress REST API 获取原始 HTML 输出
【发布时间】:2016-05-27 17:02:31
【问题描述】:

我正在使用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 page builder plugin

【问题讨论】:

  • 这里有同样的问题。我一直在尝试使用内容过滤器将其转换为 HTML。我也在支持论坛上发帖,所以我希望在那里或这里得到回应。 :) WP REST API support forum post

标签: php json wordpress api rest


【解决方案1】:

在这里找到并回答: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

【讨论】:

  • 我如何获得 CSS,rest api 没有来自 Visual Composer 的 CSS?
  • @GeorgeAlvis:我修改了我的答案,因此它现在为您提供了一个包含自定义 CSS 的 REST 响应。 WPB 将自定义 CSS 存储在 meta 中,而不是在内容中,这就是为什么您在内容请求中没有得到它的原因。 meta 可以一个一个地添加,不过 - 这就是我所做的。
  • $output['rendered'] = apply_filters( 'the_content', get_the_content()); 感谢您的回答,我正在从上面的行中检索页面内容,但现在我也希望 api 中的页面 CSS 而不是自定义 CSS。我该怎么做 ? TIA
  • 它在答案的 EDIT 部分 - 向 content 添加一个新字段,或向 REST 响应添加一个新字段。跨度>
  • 我没有使用自定义 CSS,但希望 API 中可以使用可视化作曲家元素 CSS。 @muka.gergely
【解决方案2】:

但是,聚会迟到了大约 2 年,但以下方法对我有用:

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

以防万一有人想知道。

【讨论】:

  • 这应该如何为您工作?你添加了一些过滤器吗?不清楚。
  • 我没有添加任何过滤器,我只是从 db 获取文本并尝试获取没有短代码的原始 html...
猜你喜欢
  • 2015-07-15
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
相关资源
最近更新 更多