1

I am trying to reduce the loading speed of my webpage. Google PageSpeed Insights tells me to optimize my images. In the following code, how can I set an image size so that if the uploaded image is 99999x99999px the rendered image is maximum 427px wide?

<?php
if ( has_post_thumbnail() ) {
    echo '<a href="' . get_permalink($post->ID) . '" >';
    the_post_thumbnail();
    echo '</a>';
} else {
    echo '<a href="' . get_permalink($post->ID) . '" ><img src="'. get_stylesheet_directory_uri() . '/img/fallback-featured-image.jpg" /></a>';}
    ?>

I would like Wordpress to handle this automatically so that I do not have to worry about cropping my images before I upload. It is also always nice to have the original size, but We do not want the user to wait for such a large image to load.

0

In your functions.php you want to issue a call to set_post_thumbnail_size()

https://codex.wordpress.org/Function_Reference/set_post_thumbnail_size

As with add_image_size, you provide the target width, height & whether you want the image hard cropped to these dimensions. So, for example,

set_post_thumbnail_size(427, 427, true);

will crop all your thumbnails to be a maximum of 427px high or wide, depending on aspect ratio of the original.

If you use

set_post_thumbnail_size(427, 9999);

then your images will be scaled to 427px wide without being cropped.

  • Thanks but, will this affect the code I posted? How can I get this to affect the code? – Arete May 18 '16 at 23:26
  • You put that line into your theme's functions.php and that tells WP to create a version of your image at that size when you upload a new image. It also tells WP to use that size whenever you call the_post_thumbnail() so your posted code won't need changing. You will need to tell WP to remake any images that you've uploaded. I use the Regenerate Thumbnails plugin, but there are others. en-gb.wordpress.org/plugins/regenerate-thumbnails – Andy Macaulay-Brook May 19 '16 at 8:23
  • Just in case anybody else finds this I just wanted to say that I also had to use the add_image_size function – Arete May 22 '16 at 15:26
  • Interesting. You shouldn't need to. Did you use add_theme_support? – Andy Macaulay-Brook May 22 '16 at 15:29

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.