Liz Nix

Category: Web Dev

Responsive Background Images Using the WordPress Featured Image

Recently, I wanted to create responsive background images using WordPress’s featured image feature.

One of the handy features of the WordPress media uploader is that it automatically creates multiple instances of your image at different dimensions. Thumbnail, medium, large and full images are available by default and it’s easy to add your own custom sizes.

The design for the site I was working on called for full width background images in the header. I wanted to use the smallest file size that would still look great depending on the device / viewport width, and still allow the client the ability to update the background image easily. I decided to use the featured image to allow the client to dynamically set the image on each page, and media queries to choose the WordPress generated image size for the current display width. Here’s the basic recipe.

First, in functions.php make sure your theme supports thumbnails, look for add_theme_support( 'post-thumbnails' );
and then declare any sizes you need in addition to the defaults using add_image_size(); inside your theme’s setup function. Parameters are the name and width (and optional height if you want your image to be cropped), for example:

	add_image_size( 'extra-large', 1000);
        add_image_size( 'xx-large', 1600);

You’ll need to use PHP to dynamically create the CSS, so if the featured image has been set add a <style> element to to your header.php like so:


<?php if (has_post_thumbnail($post->ID)){ ?>
<style>
body .site-header{
	background-image: url(<?php echo get_the_post_thumbnail_url($post->ID, 'large'); ?>);
}
@media (min-width:768px){
	body .site-header{
		background-image: url(<?php echo get_the_post_thumbnail_url($post->ID, 'extra-large'); ?>);
	}	
}
@media (min-width:1200px){
	body .site-header{
		background-image: url(<?php echo get_the_post_thumbnail_url($post->ID, 'xx-large'); ?>);
	}	
}
</style>
<?php } ?>

That’s all there is to it. For quick reference here are the default sizes if you’ve only enabled theme support for thumbnails:


the_post_thumbnail('thumbnail');       // Thumbnail (default 150px x 150px max)
the_post_thumbnail('medium');          // Medium resolution (default 300px x 300px max)
the_post_thumbnail('large');           // Large resolution (default 640px x 640px max)
the_post_thumbnail('full');            // Original image resolution (unmodified)

Third party code breaks layout, CSS to the rescue!

My friend messaged me today for help with a css problem. He has a third party form built in tables, and using dev tools we could see the form fields overlap the form container on mobile sizes.

before

Not only are the input fields overlapping the container, they are also overlapping the the required field indicator asterisks, which live in their own table cells. My first thought was that it would be nice have the inputs below the labels on mobile sizes. I achieve that by setting the table cells to display:block like so:

#tableId td{
display:block;
}

The result looked like this.

Form formatting solution, step one

Not very pretty, but a step in the right direction. Next I wanted to get the label and required field indicators up on the same line, which I did like this.

#tableId td:nth-child(-n+2){
	float:left;
	}

I had to refer to css-tricks.com/useful-nth-child-recipies/ to remember the nth child syntax. At first I was going to target those two elements with #tableId td:nth-child(2), #tableId td:first-child, but then I thought, “no! There’s a better way.” Why write extra code, right?

The result?
form-getting-close
Getting closer.

At this point I just want to tighten things up. Unfortunately there’s an inline declaration for width on the span holding the label (should be <label> not <span>, but I can’t change that either), so I have to use !important in my css solution. I also decided to decrease the height of the table cells holding the label and asterisk so they’re clearly grouped with their corresponding inputs, so I added a height declaration to the definition I made in the previous step, and a new definition for the span.

#tableId td:nth-child(-n+2){
	float:left;
	height:2em;
	}
#tableId td span{
	width:auto!important;
}

Now the form looks beautiful.
Beautiful Final Form

Of course, I wrapped the whole thing in a media query so these styles are only in play where the layout broke in the first place, which was right about 420px. Cool.

The final code I sent over to my friend looked like this.


@media (max-width: 420px){
	#tableId td{
		display:block;
	}
	#tableId td:nth-child(-n+2){
		float:left;
		height:2em;
	}
	#tableId td span{
       		width:auto!important;
   	}	
}

My friend said, “that worked like a dream,” and “if you’re blogging, this would make a great test case.” So here we are. He was using vanilla css, but if you want to use sass it’s even more succinct:

@media (max-width: 420px){
	#tableId td{
		display:block;
		&:nth-child(-n+2){
			float:left;
			height:2em;
		}
		span{
       			width:auto!important;
   		}
	}	
}

Well, there you have it. I hope you enjoyed reading about this as much as I enjoyed doing it. CSS is so much fun 🙂

Flexnav is clearly superior to Bootstrap Nav

I just released the starter theme that this site is based on with one very important change, I used Flexnav by Jason Weaver instead of Bootstrap’s built in navbar.

Flexnav solved several key issues with the BS (3.x) navbar which, frankly, drove me nuts!

  1. Flexnav allows for basically unlimited subnav depth out of the box.
  2. Drop down parent items can be actual links
  3.  Hover reveal for desktop
  4. Installation is easier – there is no need for a bunch of extraneous classes to nest subnavs so there is no need for a complicated nav walker class on your wp_nav_menu function.
  5. The code is more elegant for its simplicity

I’m curious to find out whether BS 4 will give me reason to switch back, but I doubt it because Flexnav is everything I ever wanted in a responsive nav menu. You can get it from jasonweaver.name/lab/flexiblenavigation/

Well that was somewhat embarrassing

You probably didn’t notice, but my site was serving a 500 error since last Sunday. Today is Friday (well it will be in 15 minutes). I became aware of the error on Tuesday.

The error was not the result of my implementation of HTTPS using CloudFlare, that went swimmingly. It’s because I switched back to another project I was working on and began editing MY .htaccess file with changes for the other project, and I didn’t notice because I was falling asleep at the keys trying to get everything done before my kids woke up!

Liz Code

My boss gave me one of the greatest compliments of my professional career yesterday. He asked who would be theming our latest project and when I said I would be, he said “good. I want this to be Liz Code.”

Filtering your custom post type archive results

I’m working on a custom post type with lot’s of custom meta data.

Today I accomplished filtering my post archive by user input, either entering a name into a text filed, or choosing a taxonomy term for a drop down. I had to switch from using get_posts to query_posts to make use of the query_posts search parameter, which saves me from manually having to sanitize the input and match the query string. Which is great, because I don’t know how to do that yet. Long story short, foreach became if … while … and everything else remained exactly the same.

My category select was another challenge to overcome. Even though WordPress has a really cool built in function wp_dropdown_categories it wasn’t working for me because I wanted additional options, not just the terms list. I ended up using get_terms instead and putting my term slug and term name values in the appropriate place and it works beautifully. This was after I almost gave up and hard-coded my list since I was trying to use get_the_terms at first until I realized get_the_terms is obviously post-specific which is why I used it in my post results, but get_terms applies to the whole taxonomy that I specify.

 

I Hate Bootstrap

The thing that bugs me about Bootstrap is that it puts so much of the layout and style information back into html, when the beauty of css was that it got most of the extra code out of HTML and left the content nice and clean. Now it’s all junked up again with extra nested divs for the grid to work. It starts to feel like way back when we were building site layouts with tables. It’s ridiculous. . .

. . . And this mentality kept me Bootstrap-resistant for a long, long time. I maintained fiercely that the framework or lack thereof for the start of a web build should be “developer’s choice.” Every developer has their own personal work flow and who am I to impede on that?

Well, who I am is the leader of a web production department, and as such my job requires me to set aside my ego and listen to the needs of my team and of the company. So when the need for a standard became too great to ignore, I had to freeze my personal bias and view the matter from as objective a perspective as possible.

The Break Point

Our build process became bogged down. If a developer needed to jump into a build in progress, they would often decide it was easier just to scrap the previous dev’s code and start over. Site maintenance became difficult too because a code change in one viewport size often meant something broke in another. We needed to get faster, and have more flexibility and more scalability.

Some of my developers had already adopted Bootstrap and their development time over the course of a handful of web builds was cut in half. Even I had to admit that once I stopped fighting the grid system, development became faster and easier. Maintenance on responsive sites is far more predictable as well. So Bootstrap became the natural choice for our department’s standard.

Light Bulb Moments

When just starting out with it, my opinion of Bootstrap is that it was bloated. Way too much extraneous code for most standard web applications. Learning that I could pull Bootstrap core css from their CDN significantly eased this concern. After that I found that I could develop I site on bootstrap with less than 300 lines of custom css code. The smaller css file is incredibly easy to manage. This greater ease of layout and styling has afforded me the opportunity to play more with fun things like JQuery, post-css, and modular-scale. So, at the end of the day, I have to say that I love Bootstrap now, at least as much as I hate it.