phpwordpressadvanced-custom-fieldswordpress-rest-apiacfpro

Wordpress rest API: How do I append all ACF of a Post Object?


Im working with the followings:

  1. Nuxt 2.15.7 for frontend development
  2. Wordpress 5.8
  3. CPT 1.9.2
  4. Advanced Custom Fields PRO 5.9.9
  5. ACF to REST API 3.3.2
  6. ACF to REST API Recursive Deactivated at this moment.

Situation:

I have two CPTs Hiking Routes and Landmarks, both of them have Custom Fields. In CPT Landmark, Im trying to pull data from Hiking Route as post object, so I can show the details such as Route length and Route colour which are custom fields. But unfortunately, I was only able to get the generic post data without any custom fields. Note: Im using nuxt to build the frontend so Im trying to get the result in rest api.

I have tried various solutions with and without ACF to REST API Recursive plugin. A very resourceful thread is here https://github.com/airesvsg/acf-to-rest-api/issues/109

I would really appreciate if anyone explains exactly how I can achieve this.

Thank you in advance.

Note: If you think question can be improved, please do it.


Solution

  • if i understand what your looking for i came across this issue a while ago and added something along these lines, you may need to mod this but add to functions file

    add_filter( 'acf/rest_api/{post_type}/get_fields', function( $data ) {
      if ( ! empty( $data ) ) {
         array_walk_recursive( $data, 'get_fields_recursive' );
      }
    
      return $data;
    } );
    
    function get_fields_recursive( $item ) {
        if ( is_object( $item ) ) {
            $item->acf = array();
            if ( $fields = get_fields( $item ) ) {
                $item->acf = $fields;                   
                array_walk_recursive( $item->acf, 'get_fields_recursive' );
            }
        }
    }