Last active
August 16, 2018 14:19
-
-
Save morgyface/d1b15423ff934700b8f6be31dc941f09 to your computer and use it in GitHub Desktop.
WordPress | Featured image or fallback source
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.phpfile and then use it in your templates like this:<img src="<?php echo feat_img_fallback($post->ID, 'medium'); ?>" alt="Image">The
$image_sizevariable 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.pngin this example) and save it in a directory calledimagesin 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.