Frontend Development + PHP, Javascript & React

Easy Responsive Featured Images In WordPress


Josie Flynn

on 11/1/2016

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:

Setting the '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.

Share to

Related Posts

Dive into the Sanity Structure Builder

By: Mark Biek on 6/13/2021

Sanity is the super fast, super customizable CMS that we're using as the backend for the new website. One of the more powerful concepts that Sanity is the ​Structure Builder which gives you the ability to customize how content is presented in the Sanity admin.

Read More »
Email @ 50: Email Development
Email @ 50: Email Development

By:Nick Stewart on 8/6/2021

Email development has always been the bane of a web developer's existence. You have to use outdated methods and don't have access to the full modern web to create a nice looking email that thousands of people will see. It's like asking a Nascar mechanic to create a car using only tools from the 90s - it can be done but its more than a pain.

Read More »