airesvsg / acf-to-rest-api

Exposes Advanced Custom Fields Endpoints in the WordPress REST API
https://wordpress.org/plugins/acf-to-rest-api/
1.33k stars 111 forks source link

add_filter with {type} not working #345

Closed warudin closed 4 years ago

warudin commented 4 years ago

I want to add the featured image to the REST output of a post_object, because it's not included by default. So I created the following function

function get_featured_image_of_post_object( $item, $request ) {
    if ( isset( $item['acf']['post_object'] ) ) {
        foreach ( $item['acf']['post_object'] as $key => $post_object ) {

      $post_object_id = $post_object->ID;
      $featured_image_id = get_post_thumbnail_id($post_object_id);

            if ( $featured_image_id ) {
                $item['acf']['post_object'][ $key ]->featured_media = $featured_image_id;
            }
        }
    }

    return $item;
}

If I use the function with the following hook, it's working fine (for posts):

add_filter('acf/rest_api/post/get_fields', 'get_featured_image_of_post_object', 10, 2);

But I read that it should work for all different endpoints by using {type} as well:

add_filter('acf/rest_api/**{type}**/get_fields', 'get_featured_image_of_post_object', 10, 2);

However, for me it doesn't. The added featured_media is not showing up any more. Is my assumption that this should be working wrong?

These are the details of my setup:

pixelbart commented 4 years ago

{type} is a placeholder for your own post types. You must also enter the post types you use there.

add_filter('acf/rest_api/my_post_type/get_fields', 'get_featured_image_of_post_object', 10, 2);
warudin commented 4 years ago

Hi @pixelbart

So should I add a separate filter for every post-type? Or is there a way to do it for all post-types at once?

pixelbart commented 4 years ago

@warudin

You can also simply create an array of your post types and let them pass through the filter.

$post_types = [ 'post_type_1', 'post_type_2', 'post_type_3' ];

foreach ( $post_types as $post_type ) {
    add_filter( 'acf/rest_api/' . $post_type . '/get_fields', 'get_featured_image_of_post_object', 10, 2 );
}

In WordPress there is also a function with which you can control all post types:

https://developer.wordpress.org/reference/functions/get_post_types/