Image Sizes REST Endpoint for Headless Front Ends
Adds a public /wp-json/site/v1/image-sizes endpoint listing every registered image size with its width, height and crop setting, so headless front ends can pick the right size for each layout.
Opens WPIDE on
Code
add_action( 'rest_api_init', function () {
register_rest_route( 'site/v1', '/image-sizes', array(
'methods' => WP_REST_Server::READABLE,
'permission_callback' => '__return_true',
'callback' => function () {
$sizes = array();
foreach ( wp_get_registered_image_subsizes() as $name => $size ) {
$sizes[] = array(
'name' => $name,
'width' => (int) $size['width'],
'height' => (int) $size['height'],
'crop' => is_array( $size['crop'] ) ? $size['crop'] : (bool) $size['crop'],
);
}
$response = new WP_REST_Response( $sizes );
$response->header( 'Cache-Control', 'public, max-age=86400' );
return $response;
},
) );
} );
Notes
Read-only and cached by browsers for a day; sizes added by themes and plugins are included.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.