Skip to content

Commit

Permalink
Allow REST API requests to retrieve URLs of attachments instead of IDs.
Browse files Browse the repository at this point in the history
  • Loading branch information
HTMLBurger-NG committed Feb 22, 2023
1 parent 4b6093e commit 3cef3de
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
14 changes: 14 additions & 0 deletions core/Helper/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
}
}
18 changes: 17 additions & 1 deletion core/REST_API/Decorator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 ) {
Expand Down
18 changes: 17 additions & 1 deletion core/REST_API/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down

0 comments on commit 3cef3de

Please sign in to comment.