How do I find images with no dimensions set?
-
Backstory
Using the WordPressthe_content
tag, I am running a custom function to search for all images that do not have awidth
andheight
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
andheight
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
andheight
set disappear on the page for some reason. As you can see on line three of my code, I’ve added anif
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 myif
statement? If there is a better way to identify it, please provide me your input.Thanks.
- The topic ‘How do I find images with no dimensions set?’ is closed to new replies.