1

I'm using the customizer to upload an image. The code I have below displays the full size image ok but I would like to instead display a custom size of that image that I created below that.

This is the code in my template file:

<img src="<?php echo get_theme_mod( 'image-1' , get_template_directory_uri().'/images/default.jpg' ); ?>">

This is the code in my functions.php file to add the custom size:

add_image_size( 'image-thumbnail', 525, 350, true ); 
3

Apparently, your mod is storing the complete path to the image as a string. That leaves you little alternative but to do a search and replace on the string:

$img = get_theme_mod('image-1');
if (!empty ($img)) {
  $img = preg_replace ('.(jpg|jpeg|png|gif)$','-525x350$0');
  if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';
    }
  else if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';

In words. Get the mod. If it exists search $img for the occurence of jpg|jpeg|png|gif at the end of the string and then prepend it with the image size, eg ...image-525x350.jpg. If that file does not exist, use the default. If there is no mod, also use the default.

0

Working from cjbj's answer, you may need to add delimiters to have your preg_replace work correctly:

$img = get_theme_mod('image-1');
if (!empty ($img)) {
  $img = preg_replace ('/.(jpg|jpeg|png|gif)$/','-525x350$0');
  if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';
  }
else if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';

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.