Support » Plugin: ACF Photo Gallery Field » Show custom fields in the API rest

  • Resolved walterisimo

    (@walterisimo)


    Hello everyone!
    I have installed the plugin advanced custom fields, and I am showing the fields in the API rest of the wordpress, using this code in the file function.php of the theme:

    $post_type = "post";
    function my_rest_prepare_post($data, $post, $request) {
        $_data = $data->data;
        $fields = get_fields($post->ID);
        foreach ($fields as $key => $value){
            $_data[$key] = get_field($key, $post->ID);
        }
        $data->data = $_data;
        return $data;
    }
    add_filter("rest_prepare_{$post_type}", 'my_rest_prepare_post', 10, 3);

    Then add the plugin ACF Photo Gallery Field so you can create gallery and display them in the rest API as well, but this does not happen.
    How should I do to show the image galleries that are part of the custom fields?

    The fields that I created with the plugin are:
    slogan
    description
    plans
    engineType
    seats
    performance
    price
    cilindrada
    video
    icon

    And so they look at the API rest http://admin.prototipowp.tk/wp-json/wp/v2/posts?categories=2

    The page I need help with: [log in to see the link]

Viewing 3 replies - 1 through 3 (of 3 total)
  • Did you ever find a solution to this?

    Plugin Author Navneil Naicker

    (@navzme)

    Hello
    Something like this should work

    $post_type = "post";
    function my_rest_prepare_post($data, $post, $request) {
        $_data = $data->data;
        $fields = get_fields($post->ID);
        foreach ($fields as $key => $value) {
            $_data[$key] = get_field($key, $post->ID);
    	}
    	//The helper function acf_photo_gallery contains array. Append this array to your data array
    	$_data['acf_photo_gallery'] = acf_photo_gallery('ACF_FIELD_NAME', $post->ID);
        $data->data = $_data;
        return $data;
    }
    add_filter("rest_prepare_{$post_type}", 'my_rest_prepare_post', 10, 3);

    I have added in
    $_data['acf_photo_gallery'] = acf_photo_gallery('ACF_FIELD_NAME', $post->ID);

    There must be a better was of doing this, if so please do share. It would be helpful for someone.

    Thank you very much, it worked for me.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Show custom fields in the API rest’ is closed to new replies.