Skip to content

Instantly share code, notes, and snippets.

@dphiffer
Last active August 29, 2015 14:02
Show Gist options
  • Save dphiffer/e89aefd95b5fd6cb4de6 to your computer and use it in GitHub Desktop.
Save dphiffer/e89aefd95b5fd6cb4de6 to your computer and use it in GitHub Desktop.
Using meta_query with JSON API
<?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."
);
}
/*
Pass meta_query as URL-encoded JSON
To borrow the example on http://codex.wordpress.org/Class_Reference/WP_Query
$args = array(
'meta_query' => array(
array(
'key' => 'age',
'value' => array(3, 4),
'compare' => 'IN',
)
)
);
Here's how that would look as a URL query param:
/?json=example/get_posts_by_meta_query&meta_query=%5B%7B%22key%22%3A%22age%22%2C%22value%22%3A%5B3%2C4%5D%2C%22compare%22%3A%22in%22%7D%5D
In JavaScript:
var meta_query = encodeURIComponent(
JSON.stringify([
{
key: 'age',
value: [3, 4],
compare: 'in'
}
])
);
In PHP:
$meta_query = rawurlencode(
json_encode(array(
'key' => 'age',
'value' => array(3, 4),
'compare' => 'IN',
))
);
*/
$query = array(
'ignore_sticky_posts' => true,
'meta_query' => json_decode($_GET['meta_query'], true)
);
return array(
'posts' => $json_api->introspector->get_posts($query)
);
}
}
?>
@mrunwal
Copy link

mrunwal commented Nov 5, 2014

I have tried to implement this thing..but it looks like its not working. As I am using this using javascript.
I feel instead

 $query = array(
 'ignore_sticky_posts' => true,
 'meta_query' => json_decode($_GET['meta_query'], true)
 );

it should be

$query = array(
  'ignore_sticky_posts' => true,
  'meta_query' => json_decode(stripslashes(rawurldecode($json_api->query->meta_query)), true)
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment