Codeable info

Making Images Scale with Browser Window in WordPress

Posted on by in WordPress Tutorials

In this advanced WordPress tutorial I am going to explain a couple different methods I developed for making post images size themselves automatically when the user changes the browser window’s size. I decided to share these methods mostly because this was no simple task to figure out for the first time and I was unable to find any help regarding this issue on the web. I created these two methods described below for a job that I had to do, so since there was nothing online about how to do it, I developed my own custom methods for the custom posts template I developed for my client. I have tested the methods with a few different themes and it had no issues when changing themes, so it should work no matter what theme you are using.

Prerequisites

Since this is one of my more advanced tutorials, there are some things you should know before you start. Here is a basic list of what you should know before trying this tutorial on your own:

  • PHP – Most of the code we will be writing will be PHP code, so you should have a fairly decent knowledge of PHP because, even though you can copy and paste my code examples from below, you still may need to understand PHP to be able to make minor adjustments to the code or in some cases the code may need to be placed in a slightly different place than in my examples if you are using a different theme or custom page template.
  • JavaScript – I also use JavaScript to accomplish a lot of the image resizing functions, so knowing and understanding JavaScript is also essential for customizing the code and making it function properly for different themes and page templates.
  • HTML – You should definitely at least know HTML if you attempt any of my advanced tutorials.
  • WordPress – understanding WordPress is also crucial. To do one of my advanced WordPress tutorials, you will need a better than average understanding of WordPress. Some of the things you should know include:
  • Dashboard – you should know your way around the WordPress admin fairly well.
  • Custom Templates – You will at least need to know the concepts behind custom templates. You should also know how to make a very basic custom template and/or child theme at minimum.
  • Loop – you definitely need to know and understand exactly what the WordPress loop is and how it works. You will need to know a little about how to customize the loop as well as that is essentially what you do whenever you write any code that effects how every post is displayed on a page of posts.

Understanding Posts and Images

Understanding the relationships between images and posts in WordPress can be confusing for any learning WordPress developer. I will attempt to explain it to you so that it makes sense without confusing you further. Finding image data can be done a few different ways in WordPress. There are built in WordPress functions that handle most things, but what do you do when you come across something that there is no preexisting function for? This is when you have to explore the WordPress database and the wp_posts and wp_postmeta tables or scrape data from the posts themselves to find what you need to know. Here is what you need to know in order to acquire information on images in WordPress:

  • Posts – Posts store information primarily in two tables of the WordPress database. They are the wp_posts table and the wp_postmeta table. Both of these tables contain some information about images, so if you see the information you are seeking in one of these two tables, then there is most likely a built in function to retrieve the data or you can query the database to get it if not.
  • Post ID – Understanding the Post ID system used in WordPress is crucial for any developer attempting to do custom WordPress work with images. For example, in regards to the database, everything is considered a post, not just actual posts as you see them on your blog. Everything in a post also gets a post id. Therefore, images have a post id as well. This can be confusing because when you are looking at a row with an image in the database and see the post id is there, if you are like me my first time, you might think that the post id refers to what post that image is for, not true!
  • Image Size – Information on image size can be the most difficult to locate. While there is some information in the wp_postmeta table for some of the images, there isn’t for all. Also the sizes stored in the database table are not the actual size that you specified when inserting the image into your post. Therefore, that information is useless if you are trying to get the actual image size as it is displayed in a post. I fought ith getting the actual image’s display size for a couple days before resulting to getting the information from the loop by scraping it with PHP or using the JavaScript dom. Either method works, so which you use will depend on your situation. I will explain more below in the section titled “Dynamic Image Sizing”.

Dynamic Image Sizing

Responsive WordPress themes seem to be all the rage of late. Unfortunately, one of the requirements of a responsive theme is to have all your images change size according to the size of the browser window. That means every time a window is opened or the user changes the size, there needs to be code in place to check and change the size of each image on that page. As I mentioned above, you cannot get the true image size as you set it when inserting the image into the post, from the database, so you have to scrape it with PHP or get it using the JavaScript dom. The way WordPress stores image display sizes is like this:

  1. user enters a size from the WordPress WYSIWYG editor’s upload/image link in the top left corner of the editor.
  2. The width and height entered into the editor in step one is not stored in the database. It is only stored in the HTML code for that particular post. So when you click the save button in the image upload window, WordPress updates the HTML code in the WYSIWYG editor…
  3. After saving changes from the image window, it is also necessary to click the update button for the post itself. This is the update button in the left column of the edit post screen for most people. Only after clicking the post’s update button with the image data be truly saved in the HTML of the post.

The only true way to get any image’s current display size is to get it directly from the HTML img tag’s width and height property. This can be done using PHP or JavaScript. In order to make images change width or height according to browser size, I had to set the images max width and max height CSS attributes to the display width and height entered by the user when they inserted the image into the post. The requirement for the site I was working on said that images should scale down as the window becomes smaller and they should scale up when the window becomes larger, but they can only scale up to the size entered by the person who wrote the post. That is why I needed to set the max width and height to the display width and height. The only way to do this efficiently is to loop over all of the images in the index.php file for your active theme, get the width and height and set the maxWidth & maxHeight properties with JavaScript. Both getting the display size and setting the max width and height can be done best using JavaScript. Here is a snippet of code I used to accomplish this. The following code would be called on the page load and on page resize events. The simplest way to accomplish that is to wrap the code in a function and use the “onload” and “onresize” event handlers in JavaScript to call the function. Call the function once for each event. Here is the code:

1) <?php
2) //fix post image widths:
3) var imgW = "100%";
4) var divarr = document.getElementsByClassName('entry');//array of divs with entry class:
5) var dcnt = divarr.length;//no. of entry divs
6) //loop over elements in entry divs:
7) 	for(i=0;i<dcnt;i++){
8) 	var imgarr = divarr[i].getElementsByTagName('img');//array of image tags in entry div
9) 	var icnt = imgarr.length;//no. of images found in entry div
10)		for(j=0;j<icnt;j++){
11)		imgarr[j].removeAttribute('height');
12)		imgarr[j].style.width=imgW;
13)		imgarr[j].style.display="block";
14)		}
15)	}//end for loop.
16) ?>

Here is the code above explained line for line:

  1. Opening PHP tag.
  2. Comment describing what the code does.
  3. Initialize the imgW variable to store and set the image width to resize to.
  4. Gets all of the divs with the class name of “entry” and stores them in an array named divarr for later use.
  5. Counts the number of divs in the divarr array, telling us how many “entry” divs there are.
  6. Comment to let us know we are about to start a for loop.
  7. Start of for loop to iterate over the divarr array of divs with entry class.
  8. Initialize the imgarr array and store all image tags from within the divs with the class name of entry(divarr).
  9. Stores the number of images found in the icnt variable.
  10. Starts a nested for loop to iterate over the image tags.
  11. Here I removed the height attribute from each image to force it to resize proportionately. If you only set either the width or height of an object the other attribute will set itself in proportion so this keeps images from stretching one way or the other.
  12. Here is where we set the image width to 100% or whatever you set the imgW variable to in line 3. I use 100% and make sure the images are in a container that limits the size to the width of the container which effectively makes all images the same size throughout the page in the multiple posts page, index.php(for most themes).
  13. Here I set the display attribute to block. You may or may not need to do this depending on your style settings for images in your theme. It can’t hurt though.
  14. Close the nested for loop.
  15. Close the first for loop.
  16. Close the PHP tag and we are done.

All of the code in the snippet above should be placed in the head of the document, which is most likely in your header.php file in the folder of your active theme. If the code doesn’t work, make sure your images are in a containing div that controls the width so that the image is a percentage of it’s parent div, not the entire page. If you don’t want to use the containing div, do not use percentages and consider seting the “maxWidth” and “maxHeight” JavaScript/CSS attributes instead along with the width and height. The code for setting max width and height is the same as width in line 12 above, just replace “width” with “maxWidth” or “maxHieght” and add a few similar lines of code to set all necessary attributes with CSS and JavaScript.

Handling Events in WordPress

As I mentioned earlier, you will have to wrap that snippet in a function. That is as easy as adding:
function resizeFunction {
above the code and after the opening PHP tag. Then add:
}
after the code and directly before the closing PHP tag. After the closing function bracket add the following code to initiate the function for the proper events. The function needs to be triggered any time the page loads and every time the user changes the size of the browser window which can be done like this:

window.onload = resizeFunction;

window.onresize=resizeFunction;

Of course, the function can be named anything you want, it doesn’t have to be called resizeFunction, that is just a name I chose as an example.

Summary

After reading this tutorial, I hope you have gained some insight into the way images work within posts in WordPress. You should know enough now to build a responsive WordPress site with images that size according to your browser window’s current size even if the user changes the size after the page has loaded. Good luck with your current or future WordPress project and have fun doing it!

)
Codeable info

Comments (1)

Comment by Dave Clements says:

It’s kind of a shame that something that, at least theoretically, is quite simple, should take so much effort to implement. It’s something that we could all probably explain in a few words what we desire the browser to do, but as yet, there is no simple way of telling a browser to do the same thing. Lucky we have good resources like this to rely on to bridge the gap between visions and implementation.

Codeable info