Quantcast
Channel: WordPress › Support » Forum: Hacks - Recent Topics
Viewing all articles
Browse latest Browse all 8245

Ethan Jinks O'Sullivan on "How do I find images with no dimensions set?"

$
0
0

Backstory
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 [^>]+>/i', $image_no_dimensions, $result ) ) {
        // print_r( $result ); // DEBUG: print all images that don't have a dimension

        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="%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" />

This functions works as expected. However, the images that already have a width and height set disappear on the page for some reason. As you can see on line three of my code, I've added an if statement to run the function only to images with no dimensions set:

if ( preg_match_all( '/<img [^>]+>/i', $image_no_dimensions, $result ) )

Except I am having trouble figuring out the regular expression (regex) to use to have preg_match_all identify only images with no dimensions set.

Objective
What is the regex that I would need to use to identify images with no dimensions in my if statement? If there is a better way to identify it, please provide me your input.

Thanks.


Viewing all articles
Browse latest Browse all 8245

Trending Articles