I like the gutenberg “latest posts” block. The problem I have with it is that it doesn’t hardcrop images that users upload to the posts. Is there a way to choose a hard-cropped or custom size that I have created through the add_image_size() function?
I don’t really have any code, but I think this question is on topic because it’s purely about wordpress core. I’m sorry if it isn’t!
What I have used to create my custom image size is this though:
add_action( 'after_setup_theme', 'aeroleds_image_sizes' );
function aeroleds_image_sizes() {
add_image_size( 'banner-image', 400, 300, true ); // (cropped)
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The Latest Posts block uses (wp.data.select( 'core/block-editor' ).getSettings() to get) the image sizes in the editor settings which can be filtered via the block_editor_settings hook in PHP:
apply_filters( 'block_editor_settings', array $editor_settings, WP_Post $post )Filters the settings to pass to the block editor.
And the setting name used for the image sizes is imageSizes.
So for example, to make the custom banner-image size be available in the featured image size dropdown (in the Latest Posts block’s settings):
add_filter( 'block_editor_settings', 'wpse_375600' );
function wpse_375600( $editor_settings ) {
$editor_settings['imageSizes'][] = [
'slug' => 'banner-image',
'name' => 'Banner Image',
];
return $editor_settings;
}
And in addition to that the filter being specific to the block editor, your callback can also get access to the post being edited, which is the second parameter ($post) in the filter hook as you can see above. So you could for example filter the settings only for certain posts.
Resources:
- The Latest Posts block on GitHub
-
The Block Editor’s Data »
getSettings() - Editor Filters » Editor Settings
Method 2
it looks like you have to also pass your custom image thumbnail sizes to the filter image_size_names_choose. I tried it and this works for displaying custom images sizes as choices in the latest posts dropdown:
add_filter('image_size_names_choose', function( $sizes ){
return array_merge( $sizes, [ 'banner-image' => 'banner image' ] );
});
This blog explains a similar issue, so I tried his suggestion.
https://talhasariyuerek.com/en/show-all-image-sizes-in-gutenberg-mediaupload-wordpress/
And by the way, the Gutenberg component that controls that dropdown is https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/image-size-control
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0