# 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.

- Type: PHP
- Runs: Frontend only
- Category: [Performance](https://wpide.com/library/category/performance/)
- Tags: images, cls, core-web-vitals
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/perf-content-image-dimensions/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Add Missing Width and Height to Images in Content" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
