How to Add Width and Height Dimensions to Divi Images

by | Aug 29, 2020 | Divi Hacks, Wordpress Optimization

Updated January 17, 2020 : I have confirmed that the code below still works. If you are having issues with results, ensure you clear your cache after applying the fix.

If you are not comfortable editing the code, I have developed an inexpensive plugin that will automatically override the default image module output with the fix and survive Divi Theme updates. It will be available for direct download with Studio 6AM’s new website relaunch (coming soon). In the meantime, if you are interested in the plugin please email me or comment below. – Lee.


Are you a Divi user? Ever wondered how to add width and height dimensions to Divi images?

I use Elegant Theme’s Divi builder for all of my projects. To say I love its creative magic and ease of use is an understatement. In fact, when first getting back into the website game, it quickly became my gateway drug of choice into the wonderous world of WordPress development – recovery is futile.

But, as with most things, Divi is not perfect. One of my pet peeves is the inability to add width and height dimensions on Divi images. Seems like a small thing I know, particularly in a world of responsive web design, but it drives me absolutely bonkers.

Barry Pollard from Smashing Magazine explains why in his excellent article on why Setting Height And Width On Images Is Important Again, and its all about user experience. Bad user experience leads to no user experience I say … and Google (you know, the big-brother company that pretty much controls your online potential?) agrees. In fact, they’re upping the stakes for non user-friendly websites which I go into more detail in my recent blog article Website Speed Test Alert – Battle Google’s Public of Shame.

In case you can’t tell, l ‘m super keen on WordPress optimization. Call me an “optimization freak” and I’ll shake your hand and wear the label proudly. The inability to add width and height dimensions on Divi images is bad for optimization, which is bad for user experience, and in the end our Google PageSpeed results suffer for it. Well, we simply can’t have that, can we?

If you’re reading this article, you’ve most likely scoured the internet looking for solutions to add width and height dimensions to Divi images, but none are readily available or totally outdated. Perhaps, like me, you even pinged Divi support in hopes of a magic solution, to which you were told “it is impossible” due to Divi’s responsive design approach. Ummm … pardon me? Impossible you say? Well, I took that as a challenge … as my Gramps used to say, “where there is a will, there is a way”. Below I share with you two ways to add height and width dimensions to your Divi images, and bump that page speed score up just a little more 😊

The Quick Fix: How to Add Width and Height Dimensions to Divi Images by Directly Editing the Image Module File

In your favourite text editor, open up the Divi image module file located at :

wp-content/themes/Divi/includes/builder/module/Image.php.

Around line 443 find the block of code that starts with $image_html = $multi_view->render_element and add the following  code (highlighted) to fetch the intrinsic dimensions of the image and add them to the attributes array:

list($width, $height) = getimagesize($src); ///fetch the current image intrinsic width and height
$image_html = $multi_view->render_element(
array(
'tag'      => 'img',
'attrs'    => array(
'src'   => '{{src}}',
'alt'   => esc_attr( $alt ),
'title' => esc_attr( $title_text ),
'width' => esc_attr( $width ),  //add the width as an attribute in $output var
'height' => esc_attr( $height ), //add the height as an attribute in $output var
),
'required' => 'src',
)
);

That’s it! You’re good to go.

It’s definitely not best practice to directly modify a theme’s core files, but it’s super quick if you’re in a pinch and hey, sometimes you gotta do what you gotta do. The real drawback with this one is that whenever the Divi theme is updated, you will lose your changes so make sure to bookmark this article in case you need to reference it again😉

The Lasting Fix: How to Add Height and Width Dimensions to Divi Images by Creating Your Own Extended Class

This one is a bit trickier, but not as scary as it sounds, and the real plus is it will not be overwritten with theme updates. I’ll walk you through it but before I do, a huge shout-out to Jonathan Bossenger who’s post on Building your own Divi Builder Modules got me on my way with this one!

The image module is created and rendered using PHP Classes. Each Divi module has its own extended class that groups together variables and functions (they are called property’s and methods in Classes).

For this fix, we will copy all of the code from  Divi’s Image Module class file and add the aforementioned modifications. I discovered some unexpected results using this in the builder itself, so we’ll wrap the entire class in logic that will only take affect on the front end if the user is not logged in (you know, like a page speed test or Google crawl bot 😉)

  1. Start by creating the custom image class file in your child theme directory. I called mine custom-image-module.php.
  2. In your child theme’s function.php file, add the following code to include the custom-image-module.php file:
    include_once(get_stylesheet_directory() . '/custom-image-module.php');
  3. All other changes will be made inside the custom-image-module.php file itself, so open that up and add the following code to ensure it is only included on the front end if the user is not logged in:
    if ( ! is_user_logged_in() ){ }
  4. Add a function that will wrap around the Class code and be hooked into the custom Divi et-builder-ready action, I called my function extend_divi_child_theme_setup(). So the code in your custom-image-module.php file will now look like this:
    <?php 
    
    if ( ! is_user_logged_in() ){ ///only call on front-end 
    
    function extend_divi_child_theme_setup() {
    
    ////php class code to go here
    
    } 
    
    add_action('et_builder_ready', 'extend_divi_child_theme_setup', 101); ///hook the function into the custom Divi hook }
  5. Copy the entire code in the Divi Image Module fiile located in wp-content/themes/Divi/includes/builder/module/Image.php and paste it into your custom-image-module.php file in between the curly braces of the function extend_divi_child_theme_setup.
  6. Adjust the name of the class to make it unique:
    ET_Builder_Module_Custom_Image extends ET_Builder_Module { ///create the new sub class name 
  7. Make the same code adjustments as described in the Quick Fix method above to add the width and height attributes:
    list($width, $height) = getimagesize($src); ///fetch the current image intrinsic width and height
    $image_html = $multi_view->render_element(
    array(
    'tag'      => 'img',
    'attrs'    => array(
    'src'   => '{{src}}',
    'alt'   => esc_attr( $alt ),
    'title' => esc_attr( $title_text ),
    'width' => esc_attr( $width ),  //add the width as an attribute in $output var
    'height' => esc_attr( $height ), //add the height as an attribute in $output var
    ),
    'required' => 'src',
    )
    );
  8. At the very bottom replace the code that reads
    new ET_Builder_Module_Image();

    with the following code:

    $et_builder_module_custom_image = new ET_Builder_Module_Custom_Image();
    remove_shortcode( 'et_pb_image' ); //remove the original et_pb_image shortcode and replace with...
    add_shortcode( 'et_pb_image', array($et_builder_module_custom_image, '_shortcode_callback') );

    This basically creates an instance of your custom class and overwrites the original et_pb_image short code with your modified one.

That’s it! Once done your custom-image-module.php should look like this:

<?php
if ( ! is_user_logged_in() ){  ///only call on front-end

function extend_divi_child_theme_setup() {
class ET_Builder_Module_Custom_Image extends ET_Builder_Module {  ///create the new sub class name

//// all the original php class code with the width and height code adjustments


$et_builder_module_custom_image = new ET_Builder_Module_Custom_Image();
remove_shortcode( 'et_pb_image' );  //remove the original et_pb_image shortcode and replace with...
add_shortcode( 'et_pb_image', array($et_builder_module_custom_image, '_shortcode_callback') );
}
add_action('et_builder_ready', 'extend_divi_child_theme_setup', 101);  ///hook the function into the custom Divi hook 
}

Open up an incognito browser window (to by-pass your WordPress logged in status) and take a look at the page source code. If done correctly you should see the width and height attributes added to the image tag like this:

Add Width and Height Dimensions To Divi Images

Won’t Adding Width and Height Dimensions to Divi Images Break the Responsive Design?

You might assume that adding the dimensions to the image will break the responsive design of the image when viewed on a tablet or smartphone, but this is not the case. Divi uses the srcset declaration to choose which image size to use depending on the device view-port, so adding the width and height has no impact other than to let the browser know the intrinsic size of the image and reserve the appropriate space so there are no huge content shifts. If you follow best practice of sizing your images to their container, you will be Gucci and have bumped up your page speed score a bit.

That’s it for now! There may be other ways to accomplish this, so please share in the comments below solutions that have worked for you.

Happy Optimizing!

Lee

About The Author

Lee Kierstead

Lee Kierstead

Founder/Owner, Studio 6AM - Websites That Work!

Lee has over 12 years experience as a full stack developer and specializes in WordPress design, development and optimization for small business and partnering website designers. Lee lives with his loving family in Whitby, Ontario, Canada.

45 Comments

  1. Sondra Barker

    How does this work with serving webp images? I am trying to do this manually to some images but I cannot get it to work. Any help would be greatly apreciated.

    • Lee Kierstead

      Hi Sondra. It all depends on how the webp image is being served. Typically, these are done as a rewrite rule on the server itself and so even though the URl will show jpeg or png etc, the response headers are changed to serve a webp version based on the user’s browser. In any event, the source code should still define the height and width.

  2. Lisa Cowan

    Hi Lee,

    I was very happy to find this post. I’ve been charged w/optimizing a Divi site, and the auto width and height is killing me on CLS. I tried your suggestions (option 2 w/a custom module), but it looks like the Image module has been changed enough that your code no longer applies. Or, I messed up. I’m not a strong PHP programmer. Do you have an update for Divi 4.7.4?

    Thanks!
    Lisa

    • Lee Kierstead

      Hi Lisa! Yes, there have been quite a few updates since I posted the article, both from Divi and GT Metrix (now using Lighthouse for page speed assessments which has thrown a lot of sites scores into a dizzy (including my own!)). In a nutshell, I’ve found Divi and CLS do not get along. I will need to update the article in light of these. The basic development principles still apply, so its really just a matter of adjusting the code to the new reality. Hit me up via email if you need some dedicated support with your project.

  3. Coraline

    You can always tell an expert! Thanks for contributing.

  4. Ryan

    Wonderful article! We will be linking to this particularly great article on our site. Keep up the good writing. Ryan.

  5. Paka M.

    Great article…. right up until I read your response to Lisa that no longer works with the newer version of Divi (currently using v. 4.9). Is this the case and will you be updating this article soon? I’d really like to implement your fix! TIA

    • Lee Kierstead

      Thanks for your comment Paka. As I indicated at the update of the article, the fix still works as expected. Good luck implementing!

  6. Camille

    Thank you for this tip ! I followed the “Lasting fix” tutorial, but I can’t get it to work (the width and height attributes remain empty). I had an error with the _et_bb_module_image_add_src_label function from the original code in wp-content/themes/Divi/includes/builder/module/Image.php, so I removed it and the error was gone. But maybe that’s why it’s not working ?

    • Lee Kierstead

      You are welcome Camille. The code is only in play if you are not logged in and on the front end of the site. Use an incognito window to view the page (by passes logged in status) and you should see results.

  7. Tim

    I can’t believe how long it’s taken me to find this fix. This is exactly how I would approach it. The only other solutions I’ve found are basically hacks like using a custom html module to replace the image module. The worst. Thank you for taking the time to write this out. I’ll be implementing this on several of my clients Divi sites

    • Lee Kierstead

      That’s awesome Tim! Thanks for taking the time to leave a message. Good luck!

  8. Tim

    Hey this worked beautifully! I’ve isolated this to a simple file that I can include in other child themes. It’s great. I’ve posted it as a gist that anyone can simply include in their functions.php. Hopefully divi doesn’t change that module too often. Your idea of making it work only as a frontend replacement is pretty brilliant. Here’s the gist: https://gist.github.com/weroh/46e40857f0762c259711b9a49f26df41

    I’m now trying to get this to work for the divi woocommerce images gallery. Have you had any luck there? It seems like they initialize classes differently than with the regular modules.

    • Lee Kierstead

      Thanks Tim! I haven’t played with the woocommerce module, but if you can isolate the image render code, it should work. FYI, I’ve built custom plugins for the image module, blurb module and full width image module that folks can purchase for a small fee and install with the ability to activate/deactivate without having to touch the functions code. Cheers!

  9. Tim

    I have more feedback for you… class-et-builder-element.php has some notes that are relevant to this.

    * since 3.23 Add support for generating responsive animation.
    * since 3.1 Renamed from `_shortcode_callback()` to `_render()`.
    * since 1.0

    Therefore this should be renamed from….

    add_shortcode( ‘et_pb_image’, array($et_builder_module_custom_image, ‘_shortcode_callback’) );

    to…

    add_shortcode( ‘et_pb_wc_images’, array($custom_module, ‘_render’) );

    I’ve tested this and it works. _shortcode_callback() is now considered a deprecated function. See /divi/includes/builder/deprecations.php

  10. Tim

    Uh…sorry I copied from the wrong script. I meant to write this should be renamed from…

    add_shortcode( ‘et_pb_image’, array($et_builder_module_custom_image, ‘_shortcode_callback’) );

    To

    add_shortcode( ‘et_pb_image’, array($et_builder_module_custom_image, ‘_render’) );

    • Lee Kierstead

      Great sleuthing Tim! Thanks so much for sharing.

  11. Tim

    Hey Lee,
    Great news! I found the answer to the WooCommerce product images with Divi. Turns out, it’s a WooCommerce issue and not a Divi one.

    Here is the related bug report:
    https://github.com/woocommerce/woocommerce/issues/25461

    • Lee Kierstead

      Thanks Tim!

  12. mai

    sos un genio, gracias!

    • Lee Kierstead

      No estoy seguro acerca de la genialidad, ¡pero gracias! Me alegro de que le haya resultado útil.

  13. Maia

    jaja muchas gracias de todos modos. Una consulta, este fix me funcionó perfecto para todas las imágenes del sitio, menos para el logo. Que cambios debería hacerle para que funcione también con el width y height del logo? Gracias nuevamente, saludos. Mai

    • Lee Kierstead

      OK. That’s as far as my Spanish goes … LOL. The logo image is a data driven element, and not produced by the image module. I recommend not using the build in menu logo feature, and replace it with an image module. So, in the row you will have 2 columns, one with your image module(logo), and then one with your menu (no logo). That way, the fix will apply to your logo, which is now produced by the image module and not the menu module.

      Cheers!

  14. Taisa

    Uf, I hope they do this on their theme soon…

    • Lee Kierstead

      Agreed. There are many improvements that Nick has alluded too, but never with a clear roadmap and timeline. Unfortunately, Web Vitals are kicking Divi user’s butts when it comes to performance. I have helped many clients get a handle on this in the meantime by reducing CLS and LCP scores.

  15. Vincent

    Would be very interested in getting the plugin you have developed to fix the image width height issue.

    Is the plugin available for purchase / download anywhere ?

    • Lee Kierstead

      Hi Vincent. I’m still working on building out my online store (developing my own lightweight ecommerce plugin to battle WOO bloat ;). In the meantime, feel free to email me and I can send it to you. Have a great day!

  16. Dave Wilson

    I would like try the plugin which you have created, will you please let me to try the hands on ?

    • Lee Kierstead

      Hi Dave. I sent you an email. Cheers!

      • Dave Wilson

        I didnt’ got any email, waiting eagerly to test the plugin

        • Lee Kierstead

          Hi Dave.

          I did send an email to the email used upon comment registration. Please check your junk/spam folders as they sometimes end up there. You can also email me at info@studio6am.com with the details and I will definitely get back to you. Cheers.

  17. Christian

    Hi Lee, is it possible to test your plugin? Or is it already public available?
    Thanks!

    • Lee Kierstead

      Hi Christian. Yes my plugins are available, just not in an online store yet. I will send you an email with the details. Cheers.

  18. Richard

    Hi Lee,

    Just came across this article as experiencing the same issues, I would be very keen to try your plugin please.

    • Lee Kierstead

      Thanks for the note Richard. I will send you an email with details. Please check your junk or promotions email folder if you don’t receive it in your inbox. Cheers.

  19. aya frenkel

    I have the same problem
    Can’t get a good CLS score just because of the height and width of the image.
    I would be very happy to try your plugin
    thank you

    • Lee Kierstead

      Hi Aya! Thanks for your comment. I sent you an email regarding the plugin(s). Please check your spam folder if you don’t see it.

  20. Chris

    Hello Lee, I have used this and it breaks my site. I’m using Divi 4.5.3
    I have tried everything, any ideas?

    • Lee Kierstead

      Hi Chris. There are multiple possibilities as to why the code breaks your site.. most likely a syntax error or wrong character encoding on a cut and past. If you are interested, I have packaged this as a plugin for purchase that will work with your version of Divi -just send me an email at infostudio6am.com. I will 100% respond, so if you don’t see my email in your inbox, check your bulk/promotions folders. Cheers!

  21. Chris de Carteret

    Hi Lee
    Is the plugin suitable for the current version fo Divi and if so can I have details on obtaining a copy
    Chris

    • Lee Kierstead

      Hi Chris. Thanks for dropping by. I have sent you an email with the detials.

  22. Spencer Taylor

    Hi Lee, thanks for this fantastic article! It looks like the code was working on slightly older versions of Divi, and I’m trying it in July of 2022. Is there any chance you will update the code for newer Divi websites in the article? CLS always seems to be an issue with Divi. It’s one of my few nitpicks with it.

    • Lee Kierstead

      Hi Spencer. Thanks for the kind words! As of Divi version 4.9.6, they have removed the auto height and width attributes which enables WordPress to backfill the required/missing attributes, so it should no longer be an issue for you. If its not working it could be a caching or performance plugin issue. Let me know if you need some professional help to resolve the issue.

  23. Jackson

    Could it really be true that it’s almost 2023 and this hack is still required? Furthermore, it requires calling the getimagesize() function on every image?

    • Lee Kierstead

      Hi Jackson.

      As of Divi version 4.9.6, they have removed the auto height and width attributes which enables WordPress to backfill the required/missing attributes, so it should no longer be an issue for those using 4.9.6 and above. For others, yep!