expose new image sizes to javascript and properly get specified image sizes in react

This commit is contained in:
2026-01-05 17:23:59 +00:00
parent abde60aecc
commit 8bd7186f97
6 changed files with 67 additions and 31 deletions

View File

@@ -7,9 +7,35 @@ class RestAPI
{
public function __construct()
{
add_filter( 'wp_prepare_attachment_for_js', [$this, 'image_sizes'], 10, 3 );
add_action( 'rest_api_init', [$this, 'blocks']);
}
public function image_sizes( $response, $attachment, $meta )
{
if ( empty( $response['sizes'] ) || empty( $meta['sizes'] ) ) {
return $response;
}
$custom_sizes = [ 'hero', 'lazy' ];
foreach ( $custom_sizes as $size ) {
if ( ! empty( $meta['sizes'][ $size ] ) ) {
$response['sizes'][ $size ] = [
'url' => wp_get_attachment_image_url( $attachment->ID, $size ),
'width' => $meta['sizes'][ $size ]['width'],
'height' => $meta['sizes'][ $size ]['height'],
'orientation' =>
$meta['sizes'][ $size ]['height'] > $meta['sizes'][ $size ]['width']
? 'portrait'
: 'landscape',
];
}
}
return $response;
}
public function blocks( )
{
$restBase = 'badegg/v1';
@@ -76,5 +102,4 @@ class RestAPI
['label' => __('Darkest', 'badegg'), 'value' => 'darkest' ],
];
}
}

View File

@@ -167,7 +167,10 @@ function cors() {
}
$image_srcset = new Utilities\ImageSrcset;
$image_srcset->add(['name' => 'hero', 'width' => 1920, 'height' => 1080]);
add_image_size('lazy', 50, 50);
add_image_size('hero', 1920, 1080, true);
add_action('after_setup_theme', function(){
$image_srcset = new Utilities\ImageSrcset;
$image_srcset->add(['name' => 'hero', 'width' => 1920, 'height' => 1080]);
add_image_size('lazy', 50, 50);
add_image_size('hero', 1920, 1080, true);
});