Skip to content

Instantly share code, notes, and snippets.

@ChrisLTD
Last active August 29, 2015 14:13
Show Gist options
  • Save ChrisLTD/19e1198a441901bd46b8 to your computer and use it in GitHub Desktop.
Save ChrisLTD/19e1198a441901bd46b8 to your computer and use it in GitHub Desktop.
<?php
/**
* Attaches ACF fields to single posts
*
* Filters output from http://wordpress.org/extend/plugins/json-api/o
* Requires ACF plugin
*/
function attach_acf_fields($response) {
// We need ACF plugin
if( !function_exists('get_fields') ) {
return $response;
}
// Only do magic on single post
if( !isset($response['post']) ) {
return $response;
}
// Add fields to parent post
add_acf_fields($response['post']);
add_post_thumbnail($response['post']);
// If this is a local guide, attach places post to the response
if( $response['post']->type == 'local-guides' && isset($response['post']->acf_fields['places']) ) {
add_related_posts($response['post'], 'places');
}
return $response;
}
add_filter('json_api_encode', 'attach_acf_fields');
/**
* Adds all ACF fields to post object
* @param post object
* @return void
*/
function add_acf_fields(&$post){
$post->acf_fields = get_fields($post->ID);
}
/**
* Adds post thumbnail(s) to post object
* @param post object
* @return void
*/
function add_post_thumbnail(&$post, $sizes = false){
// You can pass an array containing the sizes that you wish to retrieve. ie: array('thumbnail', 'large');
if( isset($sizes) && $sizes == true && is_array($sizes) ) {
$thumb_sizes = $sizes;
}
else {
$thumb_sizes = get_intermediate_image_sizes();
}
foreach($thumb_sizes as $size) {
$thumbs[$size] = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), $size );
}
$post->thumbnails = $thumbs;
}
/**
* Add related posts and their all ACF fields and thumbs to post object
* @param post object
* @param string related_post_field
* @return void
*/
function add_related_posts(&$post, $related_post_field){
if( !isset($post->acf_fields[$related_post_field]) ){
return;
}
foreach($post->acf_fields[$related_post_field] as &$related_post){
add_acf_fields($related_post);
add_post_thumbnail($related_post);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment