Skip to content

Instantly share code, notes, and snippets.

@mathetos
Created December 22, 2013 05:08
Show Gist options
  • Save mathetos/8078693 to your computer and use it in GitHub Desktop.
Save mathetos/8078693 to your computer and use it in GitHub Desktop.
3 factor Featured Image Fallback in WordPress
/*
* This code allows your posts to have a fallback featured image based on your category.
* It requires manual upload of the featured images. In this case it assumed /category-images to have
* been created in the root WP install directory.
* It is based on this tutorial at WPBeginner:
* http://www.wpbeginner.com/wp-themes/set-fallback-featured-image-based-post-category-wordpress/
* The original tutorial assumed all categories have a featured image.
* This codes inserts a div (to be styled) when there is also no featured image for the category.
* Nathan Briggs was instrumental in implementation of the file_exists method.
*/
<?php if ( has_post_thumbnail() ) : ?>
<?php the_post_thumbnail(); ?>
<?php else :
$category = get_the_category();
$featured = ABSPATH . 'category-images/' . $category[0]->category_nicename . '.jpg';
if (file_exists($featured)) {
clearstatcache(); ?>
<img src="<?php bloginfo('url'); ?>/category-images/<?php echo $category[0]->category_nicename ; ?>.jpg" alt="<?php the_title(); ?> category header" class="category-thumb" />
<?php
} else {
clearstatcache();
echo '<div class="featured">
<h1>CYS Resources for <span>' . $category[0]->category_nicename . '</span></h1>
</div>';
}
?>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment