0

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">
2
  • Will they all be images from the WordPress media library?
    – Tim Malone
    Commented Aug 4, 2016 at 21:55
  • Yes, they will be from the Media library. Commented Aug 5, 2016 at 0:04

1 Answer 1

1
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\" >" )
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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