JSON API to show Advanced Custom Fields - WordPress

后端 未结 6 2007
被撕碎了的回忆
被撕碎了的回忆 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:57

    Update for Wordpress 4.7

    With the release of Wordpress 4.7 the REST functionality is no longer provided as a distinct plugin, rather its rolled in (no plugin required).

    The previous filters don't appear to work. However the following snippet does (can be in your functions.php):

    >= PHP 5.3

    add_filter('rest_prepare_post', function($response) {
        $response->data['acf'] = get_fields($response->data['id']);
        return $response;
    });
    

    < PHP 5.3

    add_filter('rest_prepare_post', 'append_acf');
    
    function append_acf($response) {
        $response->data['acf'] = get_fields($response->data['id']);
        return $response;
    };
    

    Note the filter is a wild card filter, applied like

    apply_filters("rest_prepare_$type", ...
    

    so if you have multiple content types (custom), you will need to do:

    add_filter('rest_prepare_multiple_choice', 'append_acf');
    add_filter('rest_prepare_vocabularies', 'append_acf');
    
    function append_acf($response) {
        $response->data['acf'] = get_fields($response->data['id']);
        return $response;
    };
    

    Note It appears that rest_prepare_x is called per record. So if you are pinging the index endpoint, it will be called multiple times (so you don't need to check if its posts or post)

提交回复
热议问题