WP REST API查询多种post类型


WP REST API query multiple post types

我正在尝试使用WP REST API从多个帖子类型检索帖子。通过这样做,我没有问题从一个帖子类型book获取提要:

http://example.com/wp-json/posts?type=book&filter[posts_per_page]=10

现在我想扩展馈送以获得bookmovie。这只给了我最后一个指定的类型:

http://example.com/wp-json/posts?type=book&type=movie&filter[posts_per_page]=10

这给我一个错误:

http://example.com/wp-json/posts?type[]=book&type[]=movie&filter[posts_per_page]=10

我应该如何处理这个?

谢谢!

编辑:修正语法,以匹配我实际拥有的。以下是我在使用此语法http://example.com/wp-json/posts?type[]=book&type[]=movie&filter[posts_per_page]=10时得到的错误:

警告:urlencode()期望参数1为字符串,数组在/home/newbreak/public_html/wp-includes/format .php 4128行

警告:无法修改报头信息-报头已经由(输出开始于/home/newbreak/public_html/wp-includes/formatting.php:4128)在/home/newbreak/public_html/wp-content/plugins/json-rest-api/lib/class-wp-json-server.php第587行发送

警告:无法修改报头信息-报头已经由(输出开始于/home/newbreak/public_html/wp-includes/formatting.php:4128)在/home/newbreak/public_html/wp-content/plugins/json-rest-api/lib/class-wp-json-server.php第587行发送

警告:无法修改报头信息-报头已经由(输出开始于/home/newbreak/public_html/wp-includes/formatting.php:4128)在/home/newbreak/public_html/wp-content/plugins/json-rest-api/lib/class-wp-json-server.php第587行发送

警告:无法修改报头信息-报头已经由(输出开始于/home/newbreak/public_html/wp-includes/formatting.php:4128)在/home/newbreak/public_html/wp-content/plugins/json-rest-api/lib/class-wp-json-server.php第587行发送

警告:无法修改报头信息-报头已经由(输出开始于/home/newbreak/public_html/wp-includes/formatting.php:4128)在/home/newbreak/public_html/wp-content/plugins/json-rest-api/lib/class-wp-json-server.php第587行发送

警告:无法修改报头信息-报头已经由(输出开始于/home/newbreak/public_html/wp-includes/formatting.php:4128)在/home/newbreak/public_html/wp-content/plugins/json-rest-api/lib/class-wp-json-server.php第587行发送

当我将类型作为数组type[]发送时,我只得到错误。

您还可以尝试注册一个额外的端点,这样您就不必在每个请求中添加那么多查询参数。我使用的是最新版本的WP REST API插件。

对于自定义内容类型"movies",可以设置端点为wp-json/wp/v2/movies

add_action('rest_api_init', 'register_movies');
function register_movies() {
  $movies_custom_fields = array(
    'director',
    'genre'
  );
  foreach ($movies_custom_fields as $key) {
     register_rest_field('movies', $key, array(
     'schema'          => null,
     'get_callback'    => 'get_movies_data',
   ));
  }
}
function get_movies_data( $object, $field_name, $request ) {
   return get_post_meta( $object[ 'id' ], $field_name, true );
}

关于为不同内容类型添加自定义端点的更多文档,请参见WP REST API V2文档站点。

我们有一个类似的需求,我们只有一个段符,需要查询/查找post/page/article数据。

我们已经构建了一个wordpress api v2插件来查询多个帖子类型。

下面是插件代码https://github.com/elevati/wp-api-multiple-posttype