diff --git a/core/Helper/Helper.php b/core/Helper/Helper.php index eb376cca..04fc71f0 100644 --- a/core/Helper/Helper.php +++ b/core/Helper/Helper.php @@ -706,4 +706,18 @@ public static function get_active_sidebars() { return $sidebars; } + + public static function get_attachments_urls( $media_files ) { + if ( empty( $media_files ) ) { + return is_array( $media_files ) ? [] : ""; + } + + if ( ! is_array( $media_files ) && (int) $media_files > 0 ) { + return wp_get_attachment_url( $media_files ); + } + + return array_map( function( $media_file ) { + return wp_get_attachment_url( $media_file ); + }, $media_files ); + } } diff --git a/core/REST_API/Decorator.php b/core/REST_API/Decorator.php index 03013068..0081742f 100644 --- a/core/REST_API/Decorator.php +++ b/core/REST_API/Decorator.php @@ -57,7 +57,23 @@ public function register_fields() { $getter = function( $object, $field_name ) use ( $container ) { $object_id = self::get_object_id( $object, $container->type ); - return Helper::get_value( $object_id, $container->type, '', $field_name ); + + $value = Helper::get_value( $object_id, $container->type, '', $field_name ); + $field = Helper::get_field( $container->type, $container->id, $field_name ); + + if ( apply_filters( 'carbon_fields_rest_api_return_attachments_as_urls', false, $value, $field, $object_id ) ) { + $attachments_class = [ + "Carbon_Fields\Field\Media_Gallery_Field", + "Carbon_Fields\Field\File_Field", + "Carbon_Fields\Field\Image_Field" + ]; + + if ( in_array( get_class( $field ), $attachments_class ) ) { + $value = Helper::get_attachments_urls($value); + } + } + + return $value; }; $setter = function( $value, $object, $field_name ) use ( $container ) { diff --git a/core/REST_API/Router.php b/core/REST_API/Router.php index b7257bda..99d4848a 100644 --- a/core/REST_API/Router.php +++ b/core/REST_API/Router.php @@ -248,8 +248,24 @@ protected function get_all_field_values( $container_type, $object_id = null ) { if ( ! $field->get_visible_in_rest_api() ) { continue; } - $values[ $field->get_base_name() ] = Helper::get_value( $object_id, $container_type, '', $field->get_base_name() ); + + $value = Helper::get_value( $object_id, $container_type, '', $field->get_base_name() ); + + if ( apply_filters( 'carbon_fields_rest_api_return_attachments_as_urls', false, $value, $field, $object_id ) ) { + $attachments_class = [ + "Carbon_Fields\Field\Media_Gallery_Field", + "Carbon_Fields\Field\File_Field", + "Carbon_Fields\Field\Image_Field" + ]; + + if ( in_array( get_class( $field ), $attachments_class ) ) { + $value = Helper::get_attachments_urls($value); + } + } + + $values[ $field->get_base_name() ] = $value; } + return $values; }