webp-uploads
Last commit date
can-load.php
2 years ago
fallback.js
3 years ago
helper.php
3 years ago
hooks.php
2 years ago
image-edit.php
2 years ago
load.php
2 years ago
readme.txt
2 years ago
rest-api.php
3 years ago
settings.php
3 years ago
rest-api.php
51 lines
| 1 | <?php |
| 2 | /** |
| 3 | * REST API integration for the module. |
| 4 | * |
| 5 | * @package webp-uploads |
| 6 | * @since 1.0.0 |
| 7 | */ |
| 8 | |
| 9 | /** |
| 10 | * Updates the response for an attachment to include sources for additional mime types available the image. |
| 11 | * |
| 12 | * @since 1.0.0 |
| 13 | * |
| 14 | * @param WP_REST_Response $response The original response object. |
| 15 | * @param WP_Post $post The post object. |
| 16 | * @param WP_REST_Request $request The request object. |
| 17 | * @return WP_REST_Response A new response object for the attachment with additional sources. |
| 18 | */ |
| 19 | function webp_uploads_update_rest_attachment( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) { |
| 20 | $data = $response->get_data(); |
| 21 | if ( ! isset( $data['media_details'] ) || ! is_array( $data['media_details'] ) || ! isset( $data['media_details']['sizes'] ) || ! is_array( $data['media_details']['sizes'] ) ) { |
| 22 | return $response; |
| 23 | } |
| 24 | |
| 25 | foreach ( $data['media_details']['sizes'] as $size => &$details ) { |
| 26 | |
| 27 | if ( empty( $details['sources'] ) || ! is_array( $details['sources'] ) ) { |
| 28 | continue; |
| 29 | } |
| 30 | |
| 31 | $image_url_basename = wp_basename( $details['source_url'] ); |
| 32 | foreach ( $details['sources'] as $mime => &$mime_details ) { |
| 33 | $mime_details['source_url'] = str_replace( $image_url_basename, $mime_details['file'], $details['source_url'] ); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | $full_src = wp_get_attachment_image_src( $post->ID, 'full' ); |
| 38 | if ( ! empty( $full_src ) && ! empty( $data['media_details']['sources'] ) && ! empty( $data['media_details']['sizes']['full'] ) ) { |
| 39 | $full_url_basename = wp_basename( $full_src[0] ); |
| 40 | foreach ( $data['media_details']['sources'] as $mime => &$mime_details ) { |
| 41 | $mime_details['source_url'] = str_replace( $full_url_basename, $mime_details['file'], $full_src[0] ); |
| 42 | } |
| 43 | |
| 44 | $data['media_details']['sizes']['full']['sources'] = $data['media_details']['sources']; |
| 45 | unset( $data['media_details']['sources'] ); |
| 46 | } |
| 47 | |
| 48 | return rest_ensure_response( $data ); |
| 49 | } |
| 50 | add_filter( 'rest_prepare_attachment', 'webp_uploads_update_rest_attachment', 10, 3 ); |
| 51 |