如何使用JSON API插件通过META_QUERY获取帖子?

时间:2014-06-05 作者:Sr. Glor

我想用一种使用元查询的API方法获取帖子。我有两个自定义字段“place”和“dayoweek”,我想通过API调用检索所有对这两个字段有一些值的帖子。如果使用php,或多或少会是这样

$args = array(
    \'numberposts\' => -1,
    \'post_type\' => \'event\',
    \'meta_query\' => array(
        \'relation\' => \'AND\',
        array(
            \'key\' => \'place\',
            \'value\' => \'Melbourne\',

        ),
        array(
            \'key\' => \'dayoweek\',
            \'value\' => \'saturday\',

        )
    )

);
我的问题是。。如何使用JSON API get posts方法做到这一点?如何使用数组进行此调用。。

http://somewebiste/API/get_posts/?post_type=event&meta_key=place&meta_value=andorra&cat=1&meta_key=dayoweek&meta_value=saturday&orderby=title&order=ASC 

2 个回复
最合适的回答,由SO网友:Dan Phiffer 整理而成

这里的解决方案分为两部分。

您需要使用JSON API custom controllermeta_query 数据结构取决于您需要的健壮性,您可以使用多种方法。这是最大化方法,它允许meta_query, 将结构编码为JSON字符串。

<?php

// 1. The class name must match the filename (i.e., "foo.php" for JSON_API_Foo_Controller)
// 2. Save this in your themes folder
// 3. Activate your controller under Settings > JSON API

class JSON_API_Example_Controller {

  public function get_posts_by_meta_query() {
    global $json_api;

    if (empty($_GET[\'meta_query\'])) {
      return array(
        \'error\' => "Specify a \'meta_query\' param."
      );
    }

    $query = array(
      \'ignore_sticky_posts\' => true,
      \'numberposts\' => -1,
      \'post_type\' => \'event\',
      \'meta_query\' => json_decode($_GET[\'meta_query\'], true)
    );
    return array(
      \'posts\' => $json_api->introspector->get_posts($query)
    );
  }
}

?>
所以如果你想通过这个meta_query 作为URL编码的JSON:

$args = array(
  \'numberposts\' => -1,
  \'post_type\' => \'event\',
  \'meta_query\' => array(
    \'relation\' => \'AND\',
    array(
      \'key\' => \'place\',
      \'value\' => \'Melbourne\'
    ),
    array(
      \'key\' => \'dayoweek\',
      \'value\' => \'saturday\'
    )
  )
);
用JavaScript对其进行如下编码:

var meta_query = encodeURIComponent(JSON.stringify({
  relation: \'AND\',
  0: {
    key: \'place\',
    value:\'Melbourne\'
  },
  1: {
    key: \'dayoweek\',
    value: \'saturday\'
  }
}));
以下是URL查询参数的外观(有点笨拙):/?json=example/get_posts_by_meta_query&meta_query=%7B%220%22%3A%7B%22key%22%3A%22place%22%2C%22value%22%3A%22Melbourne%22%7D%2C%221%22%3A%7B%22key%22%3A%22dayoweek%22%2C%22value%22%3A%22saturday%22%7D%2C%22relation%22%3A%22AND%22%7D

SO网友:Sr. Glor

我(对我来说)找到了一种简单的方法,通过直接在查询上设置控制器上所需的参数。

$query = array(
      \'ignore_sticky_posts\' => true,
      \'numberposts\' => -1,
      \'post_type\' => \'event\',

      \'meta_query\' => array(
        \'relation\' => \'AND\',
        array(
          \'key\' => \'place\',
          \'value\' => $_GET[\'place\'],

          ),
        array(
          \'key\' => \'dayoweek\',
          \'value\' => $_GET[\'dayoweek\'],

          )
        ) 
      );
然后URL看起来像:json=example/get_posts_by_meta_query&place=Toronto&dayoweek=saturday

抱歉,如果我看起来像是在自动回答我的问题,我只会在有人想用其他方式回答时才这样做。

结束