Tonight, I was struggling trying to make an image resize dynamically on one of my WordPress sites based on a maximum image width. I thought I would try out some script with jQuery, since WordPress includes it in the core code. Below you will find the code that I used to make it happen, which is based on this article.

Note: This will conflict with the Featured Content Gallery plugin (and probably others, too!). Please let me know if you figure out how to get it working with that plugin! 🙂


First, make sure you initialize jQuery by calling the following function BEFORE the “wp_head();” function:

<?php wp_enqueue_script("jquery"); ?>

Second, paste the following code AFTER the “wp_head()” function call:

<script type="text/javascript">
var $j = jQuery.noConflict();
	//Configuration Options
	var max_width = 280; 	//Sets the max width, in pixels, for every image
	var selector = 'img'; 	//Sets the syntax for finding the images.  Defaults to all images.
				//For images inside of a particular element (id="abc") or class (class="abc"),
				//use '.abc img' or '#abc img' respectively.  Don't leave off the img tag!!!
	//End configuration options.  You don't need to change anything below here.
		var width = $j(this).width();
		var height = $j(this).height();
		if (width > max_width) {
			//Set variables	for manipulation
			var ratio = (height / width );
			var new_width = max_width;
			var new_height = (new_width * ratio);
			//Shrink the image and add link to full-sized image
				$(this).attr("title", "This image has been scaled down.  Click to view the original image.")
				window.location = $j(this).attr("src");
		} //ends if statement
	} //ends each function


We love to communicate: phone, email, text, Facebook, Twitter, LinkedIn, you name it.



Call Now

Enroll in Our Free Beginner WordPress Class - delivered to your Email Inbox!

Become a WordPress superstar for FREE in only minutes a day!  Our free Beginner WordPress Email Class will be delivered to your inbox!

Learn More 

You Have Successfully Enrolled! Prepare For Amazing!