Skip to content

Instantly share code, notes, and snippets.

@morgyface
Last active August 16, 2018 14:19
Show Gist options
  • Select an option

  • Save morgyface/d1b15423ff934700b8f6be31dc941f09 to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/d1b15423ff934700b8f6be31dc941f09 to your computer and use it in GitHub Desktop.
WordPress | Featured image or fallback source
<?php
// If the post does not have a featured image
function feat_img_fallback($post_id, $image_size = 'thumbnail') {
if ( has_post_thumbnail($post_id) ) {
$image_id = get_post_thumbnail_id($post_id);
$image_src = wp_get_attachment_image_src($image_id, $image_size);
$image_url = $image_src[0];
} else {
$image_url = get_bloginfo('template_directory') . '/images/placeholder.png';
}
return $image_url;
}
@morgyface
Copy link
Author

Featured image source or placeholder

Use this to stop structures crumbling.

If the post doesn't have a featured image it will return the URL of a placeholder instead.

Stick the function in your theme's functions.php file and then use it in your templates like this:
<img src="<?php echo feat_img_fallback($post->ID, 'medium'); ?>" alt="Image">

The $image_size variable is an option, without it, it will default to the thumbnail size as set in your dashboard settings.

You'll need to create a placeholder image (called placeholder.png in this example) and save it in a directory called images in your theme's root directory.

Hope it helps. There's a variation here which returns a complete image tag or generates an SVG on the fly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment