One challenge I encountered when building a new website for Kentucky Refugee Ministries was how to realize a design centered around their wonderful photography, while also allowing them to easily add new photographs in the future. WordPress offers featured images for things like page headers, but we had to go a little further to realize our vision.
Adding another image slot
We customize WordPress to empower our clients, so hard-coding background images that they couldn’t change wasn’t an option. In our solution, the client sets each page’s featured image to the larger image we use for desktops, and then sets an optional mobile image in a custom meta field.
To add this meta field, we use the CMB2 library which is excellent for quick and easy custom metaboxes. For brevity’s sake we won’t get into the installation of that library in this post, but their documentation will get you up and running.
Let’s assume we’ve already included CMB2 in our theme. Setting up the metabox just takes a couple of function calls:
'type' of our meta field to
'file' gives us an additional WordPress media upload control.
Displaying in the theme
Now that our meta field is available on all pages, we can show it in the theme. Since we’re querying this from the database, we have to rely on inline CSS. For KRM, I set up a template part that fetches the featured image and our mobile featured image, then echoes them into `background-image` declarations.
Now post authors can upload a different image for mobile when a scaled down and cropped version of the post’s featured image doesn’t look great. If your design requires it, you can expand this solution to as many breakpoints as you need by adding additional meta fields to your metabox and rules to your CSS.
What's the JAMstack?
As a front-end developer in 2020, it is time that I fulfill the FEDeral mandate that I publish words regarding the JAMStack. If you follow too many developers on Twitter, it’s likely you’ve heard about the Next Big Thing in web development, but I’d like to put this trend (fad? movement?) into context to better understand what’s truly new about this approach and whether it’s worth using.Read More »