612-293-8629 HELLO@THEMIGHTYMO.COM

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! ūüôā

Enjoy!

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();
 
$j(document).ready(function(){
	//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.
 
	$j(selector).each(function(){
		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
			$j(this).height(new_height).width(new_width);
			$j(this).hover(function(){
				$(this).attr("title", "This image has been scaled down.  Click to view the original image.")
				$(this).css("cursor","pointer");
				});
			$j(this).click(function(){
				window.location = $j(this).attr("src");
				});
		} //ends if statement
	} //ends each function
	);
 
});
</script>

PHONE, EMAIL, TEXT

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

LOCATIONS

PAYMENTS ACCEPTED

LINKS

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!