Skip to content

Instantly share code, notes, and snippets.

@dphiffer
Created December 26, 2013 17:16
Show Gist options
  • Save dphiffer/8136232 to your computer and use it in GitHub Desktop.
Save dphiffer/8136232 to your computer and use it in GitHub Desktop.
JSON API needs to be customized a bit to retrieve *all* the image attachments in a WordPress site.
// Add this snippet of code to functions.php if you want to retrieve all
// the attachments on a blog using the JSON API plugin.
// Use this API call: http://foo.com/?json=core.get_posts&post_type=attachment
add_action('json_api-core-get_posts', 'setup_attachments_filter');
function setup_attachments_filter() {
// Workaround for JSON API disallowing post_status arguments
global $json_api;
if ($json_api->query->post_type == 'attachment') {
add_action('pre_get_posts', 'allow_inherit_status');
add_filter('json_api_encode', 'encode_attachment_data');
}
}
function allow_inherit_status($wp_query) {
// Attachments inherit their post_status from whatever they're attached to.
$wp_query->query_vars['post_status'] = 'inherit';
}
function encode_attachment_data($data) {
// Returned attachment posts need to have the image URLs encoded.
global $json_api;
foreach ($data['posts'] as $index => $post) {
$data['posts'][$index] = $json_api->introspector->get_attachment($post->id);
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment