JSON API to show Advanced Custom Fields - WordPress

后端 未结 6 2011
被撕碎了的回忆
被撕碎了的回忆 2021-01-30 15:14

I am developing a magazine WordPress site that will have a json feed for a Mobile App. I set the backend up using Advanced Custom Fields with a Repeater Field for Multiple Artic

6条回答
  •  南方客
    南方客 (楼主)
    2021-01-30 15:44

    Current version of ACF prints out a custom_fields object on a call to the JSON API, containing all the fields relative to the Post or Page. I edited @Myke version to add specific custom fields from the ACF Option page to each Post or Page. Unfortunately there is not get_fields() function for the whole Option Page so you'll have to edit it depending on your fields structure.

    add_filter('json_api_encode', 'json_api_encode_acf');
    
    function json_api_encode_acf($response) {
        if (isset($response['posts'])) {
            foreach ($response['posts'] as $post) {
                json_api_add_acf($post); // Add specs to each post
            }
        }
        else if (isset($response['post'])) {
            json_api_add_acf($response['post']); // Add a specs property
        }
        else if (isset($response['page'])) {
            json_api_add_acf($response['page']); // Add a specs to a page
        }
    
        return $response;
    }
    
    function json_api_add_acf(&$post) {
        $post->custom_fields->NAME_OF_YOUR_CUSTOM_FIELD = get_field( 'NAME_OF_YOUR_CUSTOM_FIELD', 'option' );
    }
    

提交回复
热议问题