Default image for post thumbnails

I’m developing a theme that’s dependent upon there being post thumbnails of a certain size for each post. But, if the client forgets to add a thumbnail or doesn’t have one for a post, I don’t want it to break the site’s layout.

I created a function called be_no_thumbnail($size). When you run that function (with an appropriate size) it will generate a blank image of that size.

This is designed to work with the image sizes defined in Settings > Media (thumbnail, small, medium, large). You’d need a different approach for custom image sizes as their dimensions aren’t stored in the same database fields.

Here’s the function:

And here’s how I use it:

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk

Reader Interactions

Comments

  1. Ian says

    Hi Bill,
    I’ve been looking to achieve something like this. I use WordPress thumbs on my thesis site (so I can have 3 sizes of the same image), following your recommendation & tutorial.

    How can I incorporate this code into Thesis so if an image isn’t attached it calls up a default image?

  2. Ian says

    I’ve posted the function in custom-functions but not sure what I do with the second part, ie how to use it?

    • Bill Erickson says

      Let’s say you had a function you’re using to display post thumbnails on single pages:

      add_action(‘thesis_hook_before_post’, ‘be_thumbnail_single’);
      function be_thumbnail_single() {
      if (is_single()) && has_post_thumbnail())
      the_post_thumbnail(‘large’);
      }

      You would change it to incorporate the no thumbnail function.

      if (is_single()):
      if( has_post_thumbnail()) the_post_thumbnail(‘large’);
      else be_no_thumbnail(‘large’);
      endif;

  3. Cathy Tibbles says

    Would it be easier to create the test for the img in the functions file so the Genesis_Image call in the templates doesn’t need to be messed with? Is that a bad idea?

    • Bill Erickson says

      I’m not exactly sure what you’re asking here. Do you mean to create a new function like be_get_thumbnail() that checks for a thumbnail, then serves up the thumbnail or default depending on what’s available? That’s also an approach that could work.

Leave A Reply