Using the WordPress the_content tag, I am running a custom function to search for all images that do not have a width and height attribute set and insert the proper dimensions. Below is the function:

add_filter( 'the_content', 'add_img_dimensions' );

function add_img_dimensions( $image_no_dimensions ) { // Insert width & height to images missing dimensions
    if ( preg_match_all( '/<img [^>]+width=[^>]+height=>/i', $image_no_dimensions, $result ) ) {
        // Do nothing...
    }
    else {
        preg_match_all( '/(alt|title|src)=("[^"]*")/i', $image_no_dimensions, $img );
        list( $width, $height, $type, $attr ) = getimagesize( str_replace( "\"", "" , ( $img[2][0] ) ) );
        $imgname = str_replace( "\"", "" , ( $img[2][0] ) );
    }

    return sprintf( '<img src="https://wordpress.stackexchange.com/questions/236318/%s" width="%dpx" height="%dpx" />', str_replace("\"", "" , ( $img[2][0] ) ), $width, $height );
}

For example, if there is an image on one of my pages that looks like the following:

<img src="https://link.to/sum/img.jpg" alt="Image Title" />

It will then insert the width and height of the actual image:

<img width="150" height="50" src="https://link.to/sum/img.jpg" alt="Image Title" />

The function works as expected. However, all of the page’s content is replace with the first image that it finds that don’t have dimensions set.

How can I return all of the content but only change the images that don’t have a dimension?

Before and after
enter image description here

2 Answers
2

Tested and confirmed that this works:

add_filter( 'the_content', 'add_image_dimensions' );

function add_image_dimensions( $content ) {

    preg_match_all( '/<img[^>]+>/i', $content, $images);

    if (count($images) < 1)
        return $content;

    foreach ($images[0] as $image) {
        preg_match_all( '/(alt|title|src|width|class|id|height)=("[^"]*")/i', $image, $img );

        if ( !in_array( 'src', $img[1] ) )
            continue;

        if ( !in_array( 'width', $img[1] ) || !in_array( 'height', $img[1] ) ) {
            $src = $img[2][ array_search('src', $img[1]) ];
            $alt = in_array( 'alt', $img[1] ) ? ' alt=" . $img[2][ array_search("alt', $img[1]) ] : '';
            $title = in_array( 'title', $img[1] ) ? ' title=" . $img[2][ array_search("title', $img[1]) ] : '';
            $class = in_array( 'class', $img[1] ) ? ' class=" . $img[2][ array_search("class', $img[1]) ] : '';
            $id = in_array( 'id', $img[1] ) ? ' id=' . $img[2][ array_search('id', $img[1]) ] : '';
            list( $width, $height, $type, $attr ) = getimagesize( str_replace( "\"", "" , $src ) );

            $image_tag = sprintf( '<img src=%s%s%s%s%s width="%d" height="%d" />', $src, $alt, $title, $class, $id, $width, $height );
            $content = str_replace($image, $image_tag, $content);
        }
    }

    return $content;
}

Leave a Reply

Your email address will not be published. Required fields are marked *