Does anyone know how to resize the served images, so the image has a width due to the content containers width. I do not mean to resize the image via 100% width css, but instead resize the actual dimensions and size if the image itself.
For e.g.: An image in an article which has the dimensions of 400px à 300px
. But in the overview I only need 200px à 150px
. But I do not want to edit every part of my theme to do so, because there are a lot of different sizes. Is there any possibility that this works automatically?
As things like this are often requested, I’ve written a plugin named “Dynamic Image Resize”. It’s basically a plugin, but, due to it’s one-file approach, it can be used as mu-plugin or theme include without a problem. It’s main purpose is to resize single images on demand to a given height/width.
These are the arguments the “Template Tag”/function and the shortcode take:
Now you could simply set the
hwmarkup
totrue/yes/1/on
and it gets rid of theimg
-HTML tagwidth/height
-attributes, so the browser will resize it to the container width automatically. You could as well go further and simply extend the class:Note please, that this isn’t tested, but just a quick draft.
In general no, the PHP code has no way to know what image sizes you use in the CSS as PHP is being executed first on the server and only after that the CSS is executed in the browser.
Only way that might work is if you specify all the image sizes in CSS but don’t serve any images, and only a reference to their src via a data-xxxxxx attribute. After the page load you run some JS that for each image checks its CSS defined height and width and set the src of the img to a url which will dynamically generate the image in the required dimensions.
The biggest drawbacks with this approach is that images are starting to load only after the page had finished loading instead of in parallel, and that people that block JS will not see the images at all.
If the images are in the same proportions as in your question you might as well serve the bigger image and leave the scaling to the browser.
I think you just want add_image_size() and the_post_thumbnail(), e.g.,