I want to add a custom function to scan my website and automatically insert image size attributes that are missing on my pages.

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">

If img.jpg actual size is 150x50 px, the function would pick up on that and insert the proper width and height tags:

<img width="150" height="50" src="https://link.to/sum/img.jpg" alt="Image Title">
  • Will they all be images from the WordPress media library? – Tim Malone Aug 4 '16 at 21:55
  • Yes, they will be from the Media library. – Ethan Jinks O'Sullivan Aug 5 '16 at 0:04
function replaceImageMeta( $imagename ) {

    preg_match_all('/(alt|title|src)=("[^"]*")/i',$imagename, $img);//var_dump( str_replace("\"", "" , ( $img[2][0] ) ) );

    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);


So call the function with image string

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.