preg_replace to Change Image Suffix In a Loop
Working with PHP is more and more fun with each little bit and snippet I learn.
I recently learned about replacing regular expressions and messing with file extensions. In a recent theme, I had to get the image source, add an extra suffix, and keep the extension intact, all while calling the original image for a lightbox. To do that I pulled from a few different sources.
<?php $img1 = get_post_meta($post->ID, PROJECTS_IMAGE_1_KEY, true); //grabbed the img src $ext1 = pathinfo($img1, PATHINFO_EXTENSION); //grabs the file extension at the end $medium1 = preg_replace('/.'.$ext1.'/', '-450x300.'.$ext1.'', $img1 ); //replaces the extension with number and extension ?> <!-- so first, get the img src and attach lightboxness --> <li><a href="<?php echo get_post_meta($post->ID, PROJECTS_IMAGE_1_KEY, true) ?>" class="fancybox" rel="group"> <!-- then use the variable $medium1 created above to get the smaller image --> <img class="featured-img" src="<?php echo $medium1 ?>" alt="<?php echo $post->post_title ?>" /> </a></li>
By using the above code, I was able to use my custom created images and decrease load time. I also added an image size that was 450×300, that way any images I uploaded would automatically have that correct extension at the end (thanks WordPress for creating many different image sizes).
The code does this by seeing first what you want to replace (the pattern), in this case $ext1. The next bit of text is what will replace it with -450×300.$ext1 (the replacement). The final part is declaring what will be having these parts replaced (the subject), so for us it is $img1.
You may be saying, just use wp_post_thumbnail and to that I say yes. In many cases, that would be the correct thing to do. The difference here was that I was unable to call the featured image, because this was a backup in case the featured image was not set.
It is important to point out that preg_replace is the correct usage and not ereg_replace, which is deprecated.
The Links I pulled from: