Were you looking for something like this? Pushed the width and height to “mediaDetails”
add_action(
'rest_api_init',
function () {
if ( ! function_exists( 'use_block_editor_for_post_type' ) ) {
require ABSPATH . 'wp-admin/includes/post.php';
}
// Surface all Gutenberg blocks in the WordPress REST API
$post_types = get_post_types_by_support( [ 'editor' ] );
foreach ( $post_types as $post_type ) {
if ( use_block_editor_for_post_type( $post_type ) ) {
register_rest_field(
$post_type,
'blocks',
[
'get_callback' => function ( array $post ) {
$blocks = parse_blocks( $post['content']['raw'] );
foreach ( $blocks as $key => $block ) {
if ( $block['blockName'] === 'core/image' ) {
$meta = wp_get_attachment_metadata( $block['attrs']['id'] );
$blocks[ $key ]['mediaDetails'] = array(
'width' => $meta['width'],
'height' => $meta['height'],
);
}
}
return $blocks;
},
]
);
}
}
}
);
I think that might work, just based on reading over it. I ended up putting together and solution based on this blog post. It is not quite the same, as they are getting the featured image and I want every Gutenberg block that is an image, as well as any short code blocks that use a certain image component.
function add_image_attrs() {
register_rest_field('post', 'image-dimensions', array(
'get_callback' => 'getImageProperties',
'update_callback' => null,
'schema' => null,
));
}
add_action('rest_api_init', 'add_image_attrs');
function getImageProperties() {
// current Post
global $post;
// regex to get all image ID's within Gutenberg post content, initialize $matches variable, set results to that
$imageIds = array();
if(preg_match_all('<!-- wp:image {"id":(\d+)} -->', $post->post_content, $matches)) {
array_push($imageIds, $matches[1]);
};
if(preg_match_all('#wp-image-(\d+)#', $post->post_content, $matches)) {
array_push($imageIds, $matches[1]);
};
if (empty($matches[1])) {
return;
}
// map over $matches array, get metadata using each ID, return ID, width, height
$results = array_map(function($imageId) {
$image = wp_get_attachment_metadata($imageId);
return [
'id'=>(int)$imageId,
'width'=>$image['width'],
'height'=>$image['height']
];
}, $matches[1]);
return $results;
}
I hope perhaps it is useful to someone.