JSON API to show Advanced Custom Fields - WordPress

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

    Came here by searching with the same question. This isn't totally vetted yet but I think this is getting on the right path. Check it out.

    I have one less nested level than you do so this might need altered a bit. But the JSON API plugin has a filter called json_api_encode. I have a repeater called specifications that looks like this.

    http://d.pr/i/YMvv

    In my functions file I have this.

    add_filter('json_api_encode', 'my_encode_specs');
    
    function my_encode_specs($response) {
      if (isset($response['posts'])) {
        foreach ($response['posts'] as $post) {
          my_add_specs($post); // Add specs to each post
        }
      } else if (isset($response['post'])) {
        my_add_specs($response['post']); // Add a specs property
      }
      return $response;
    }
    
    function my_add_specs(&$post) {
      $post->specs = get_field('specifications', $post->id);
    }
    

    Which appends a custom value to the JSON API output. Notice the get_field function from ACF works perfectly here for bringing back the array of the repeater values.

    Hope this helps!

提交回复
热议问题