Warn About Oversized Images Before Publishing
Lists image blocks whose original file is larger than a size you set, such as 1 MB, in the block editor's publish panel, so heavy photos get replaced before they slow down the page.
Opens WPIDE on
Code
// Largest acceptable image file size in kilobytes.
$wpide_max_image_kb = 1024;
add_action( 'enqueue_block_editor_assets', function () use ( $wpide_max_image_kb ) {
$screen = get_current_screen();
if ( ! $screen || 'post' !== $screen->base ) {
return;
}
wp_register_script( 'wpide-oversized-images', false, array( 'wp-plugins', 'wp-element', 'wp-components', 'wp-data', 'wp-core-data', 'wp-editor', 'wp-block-editor' ), '1.0', true );
wp_enqueue_script( 'wpide-oversized-images' );
wp_add_inline_script( 'wpide-oversized-images', 'var wpideMaxImageKb = ' . (int) $wpide_max_image_kb . ';' . <<<'JS'
( function ( wp ) {
var el = wp.element.createElement;
var Panel = ( wp.editor && wp.editor.PluginPrePublishPanel ) || ( wp.editPost && wp.editPost.PluginPrePublishPanel );
if ( ! Panel ) { return; }
function images( blocks, list ) {
blocks.forEach( function ( block ) {
if ( block.name === 'core/image' && block.attributes.id ) { list.push( block ); }
if ( block.innerBlocks && block.innerBlocks.length ) { images( block.innerBlocks, list ); }
} );
return list;
}
function OversizedImages() {
var heavy = wp.data.useSelect( function ( select ) {
var core = select( 'core' );
return images( select( 'core/block-editor' ).getBlocks(), [] ).map( function ( block ) {
var media = core.getMedia( block.attributes.id, { context: 'view' } );
var size = media && media.media_details && media.media_details.filesize;
return size && size > wpideMaxImageKb * 1024 ? { block: block, size: size, name: media.source_url.split( '/' ).pop() } : null;
} ).filter( Boolean );
}, [] );
var selectBlock = wp.data.useDispatch( 'core/block-editor' ).selectBlock;
return el( Panel, { title: heavy.length ? 'Images: ' + heavy.length + ' over ' + wpideMaxImageKb + ' KB' : 'Image sizes', initialOpen: heavy.length > 0 },
heavy.length
? heavy.map( function ( item ) {
return el( 'p', { key: item.block.clientId }, el( wp.components.Button, { variant: 'link', onClick: function () { selectBlock( item.block.clientId ); } }, item.name + ' (' + Math.round( item.size / 1024 ) + ' KB)' ) );
} )
: el( 'p', null, 'All images are a reasonable size.' )
);
}
wp.plugins.registerPlugin( 'wpide-oversized-images', { render: OversizedImages } );
} )( window.wp );
JS
);
} );
Notes
Set $wpide_max_image_kb; the check reads file sizes WordPress stored at upload, so very old uploads without that data are skipped.
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.