Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Auto add size attributes to images WordPress

  • SOLVED

While there are plugins to remove size attributes to images, I am looking for one that does the opposite which is to automatically add size attributes to images.

So far I couldn't find one but there is a plugin called WP-Rocket that has this feature. I do have a valid license but I end up using WP Super Cache instead.

I tried to embed the code below to functions.php but doesn't work.

Can anyone fix the code below so that it can be used independently without activating WP-Rocket?


add_filter( 'rocket_buffer', 'rocket_specify_image_dimensions', 10 );
function rocket_specify_image_dimensions( $buffer )
{
/**
* Filter images dimensions attributes
*
* @since 2.2
*
* @param bool Do the job or not
*/
if ( ! apply_filters( 'rocket_specify_image_dimensions', false ) ) {
return $buffer;
}

// Get all images without width or height attribute
preg_match_all( '/<img(?:[^>](?!(height|width)=))*+>/i' , $buffer, $images_match );

foreach ( $images_match[0] as $image ) {

// Don't touch lazy-load file (no conflit with Photon (Jetpack))
if ( strpos( $image, 'data-lazy-original' ) || strpos( $image, 'data-no-image-dimensions' ) ) {
continue;
}

$tmp = $image;

// Get link of the file
preg_match( '/src=[\'"]([^\'"]+)/', $image, $src_match );

// Get infos of the URL
$image_url = parse_url( $src_match[1] );

// Check if the link isn't external
if ( empty( $image_url['host'] ) || $image_url['host'] == rocket_remove_url_protocol( home_url() ) ) {
// Get image attributes
$sizes = getimagesize( ABSPATH . $image_url['path'] );
} else {
/**
* Filter distant images dimensions attributes
*
* @since 2.2
*
* @param bool Do the job or not
*/
if ( ini_get('allow_url_fopen') && apply_filters( 'rocket_specify_image_dimensions_for_distant', false ) ) {
// Get image attributes
$sizes = getimagesize( $image_url['scheme'] . '://' . $image_url['host'] . $image_url['path'] );
}
}

if ( ! empty( $sizes ) ) {
// Add width and width attribute
$image = str_replace( '<img', '<img ' . $sizes[3], $image );

// Replace image with new attributes
$buffer = str_replace( $tmp, $image, $buffer );
}
}

return $buffer;
}

Answers (2)

2015-08-11

timDesain Nanang answers:

Hi,
I think you can use 'the_content' filter to add image dimension.
Try the following code (it can work even for external links):

add_filter('the_content', 'wpq_image_dimension');
function wpq_image_dimension($content) {

$buffer = $content;

// Get all images without width or height attribute
preg_match_all( '/<img(?:[^>](?!(height|width)=))*+>/i' , $content, $images_match );

$all_images = $images_match[0];
foreach ( $all_images as $image ) {

$tmp = $image;

// Get link of the file
preg_match( '/src=[\'"]([^\'"]+)/', $image, $src_match );

// Get image url
$image_url = ( $src_match[1] );

//get image dimension
list($width, $height) = getimagesize( $image_url );
$dimension = 'width="'.$width.'" height="'.$height.'" ';

// Add width and width attribute
$image = str_replace( '<img', '<img ' . $dimension, $image );

// Replace image with new attributes
$buffer = str_replace( $tmp, $image, $buffer );
}

return $buffer;
}


raymond comments:

Hi timDesain Nanang,

Your code works perfectly.


timDesain Nanang comments:

@Rochester Oliveira

i am sorry, my code has a bit different on these line:

//get image dimension
list($width, $height) = getimagesize( $image_url );
$dimension = 'width="'.$width.'" height="'.$height.'" ';


2015-08-10

rochester answers:

Hi!

Thanks for sending us your question. But would you mind elaborating a little bit more on what you are trying to do there? Where exactly do you want the image sizes? For which images?

Wp itself adds the images sizes when you upload them in the content field actually, so you should need no code at all, hence my question :)

Also I really feel like this could be solved via CSS, just in case if you want to send us an example of the issue you are facing (a public URL) that would be awesome.

Kind Regards,
-Roch


raymond comments:

I understand that WordPress does automatically add the width and height to the images, but I have always been manually removing them, so they don't exist on the post.

Now I implemented Lazy Loading of images and found that it is a bit annoying that the text are constantly being moved around and pushed down whenever an image that is in viewport being loaded.

To prevent the text in post from being pushed down or moved around, adding the width and height attribute to images seems to work because the browser doesn't need to recalculate in real time.

I'm not very sure but I don't think it is possible to solve it using CSS because all the images on the post are in different sizes.


rochester comments:

Ok, now I get it!

Indeed it isn't possible via CSS, but the code above won't work as well because it's relying on some of the plugin's features. Also this would probably run "on-the-fly" which would ruin your site performance. What you can do that is to add a filter that is activated when you save the post.

PLEASE run a full backup before adding this code, as it changes the saved data. Also what you could do is to save no items until you are sure that this works fine.

Also you'll need to copy this function from the plugin: rocket_remove_url_protocol; It should work without it, but performance will be low at the beginning if you have a lot of images (since the code will treat all images as external)

Please try this alternative version and let me know how it works:

add_action( 'save_post', 'wpq_specify_image_dimensions' );

function wpq_specify_image_dimensions( $id, $post ) {
$buffer = $post->post_content;

// Get all images without width or height attribute
preg_match_all( '/<img(?:[^>](?!(height|width)=))*+>/i' , $buffer, $images_match );

foreach ( $images_match[0] as $image ) {

// Don't touch lazy-load file (no conflit with Photon (Jetpack))

if ( strpos( $image, 'data-lazy-original' ) || strpos( $image, 'data-no-image-dimensions' ) ) {

continue;

}

$tmp = $image;

// Get link of the file

preg_match( '/src=[\'"]([^\'"]+)/', $image, $src_match );

// Get infos of the URL
$image_url = parse_url( $src_match[1] );

// Check if the link isn't external
if ( empty( $image_url['host'] ) || $image_url['host'] == rocket_remove_url_protocol( home_url() ) ) {

// Get image attributes

$sizes = getimagesize( ABSPATH . $image_url['path'] );

} else {

/**

* Filter distant images dimensions attributes

*

* @since 2.2

*

* @param bool Do the job or not

*/

if ( ini_get('allow_url_fopen') && apply_filters( 'rocket_specify_image_dimensions_for_distant', false ) ) {

// Get image attributes

$sizes = getimagesize( $image_url['scheme'] . '://' . $image_url['host'] . $image_url['path'] );

}

}



if ( ! empty( $sizes ) ) {

// Add width and width attribute

$image = str_replace( '<img', '<img ' . $sizes[3], $image );



// Replace image with new attributes

$buffer = str_replace( $tmp, $image, $buffer );

}

}

$post->post_content = $buffer;

wp_update_post( $post );

}


Kind Regards,
-Roch


rochester comments:

Forgot to say, all you need to do is to click any item and hit "update". You could also do it in a batch after you know that it works as you want (by selecting multiple items in your wp-admin screen).

Kind Regards,
-Roch


raymond comments:

Thanks, I do have WP Super Cache installed and activated, so the performance hit is only once during the first time visit to create the cache.

If I do not want to use the save_post action, what other options do I have so that it won't touch the database?


rochester comments:

Hi!

If you have a good caching system in place, instead of the first lines:
add_action( 'save_post', 'wpq_specify_image_dimensions' );



function wpq_specify_image_dimensions( $id, $post ) {
$buffer = $post->post_content;


Use this:
add_filter( 'the_content', 'wpq_specify_image_dimensions' );



function wpq_specify_image_dimensions( $buffer ) {


And in the end instead of:
$post->post_content = $buffer;



wp_update_post( $post );



}


Use:
return $buffer;
}


It isn't a super solution (since it relies on a good aching system) but will get you there without messing up with the db!

Kind Regards,
-Roch


raymond comments:

Hi, I've just tested your solution in a test offsite but unfortunately it did not work.
The remaining page that starts from the post gets cut off.


rochester comments:

@timDesain Nanang

That's pretty much what I've sent in my last reply.

@raymond

Please send me via private message your site URL and maybe test credentials so I can check what else could be done there

Kind Regards,
-Roch