Add Missing Width and Height to Images in Content
Adds width and height attributes to images in your posts that lack them (for example images pasted from other sites or old posts), using the real image file size, which prevents layout jumps while pages load.
Opens WPIDE on
Code
add_filter( 'the_content', function ( $content ) {
if ( false === stripos( $content, '<img' ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $content;
}
$uploads = wp_get_upload_dir();
$base = set_url_scheme( $uploads['baseurl'], 'https' );
$tags = new WP_HTML_Tag_Processor( $content );
while ( $tags->next_tag( 'img' ) ) {
if ( $tags->get_attribute( 'width' ) && $tags->get_attribute( 'height' ) ) {
continue;
}
$src = set_url_scheme( strtok( (string) $tags->get_attribute( 'src' ), '?' ), 'https' );
if ( 0 !== strpos( $src, $base ) ) {
continue;
}
$key = 'wpide_dim_' . md5( $src );
$size = wp_cache_get( $key, 'wpide' );
if ( false === $size ) {
$size = get_transient( $key );
}
if ( false === $size ) {
$path = $uploads['basedir'] . substr( $src, strlen( $base ) );
$info = ( false === strpos( $path, '..' ) && is_readable( $path ) ) ? wp_getimagesize( $path ) : false;
$size = $info ? array( (int) $info[0], (int) $info[1] ) : array( 0, 0 );
set_transient( $key, $size, MONTH_IN_SECONDS );
}
wp_cache_set( $key, $size, 'wpide' );
if ( $size[0] && $size[1] ) {
$tags->set_attribute( 'width', (string) $size[0] );
$tags->set_attribute( 'height', (string) $size[1] );
}
}
return $tags->get_updated_html();
}, 20 );
Notes
Only images stored in your uploads folder can be measured; sizes are cached per image so files are not read on every page view.
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.