Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.