php - Wordpress thumbnail as background image, with a defualt fallback
Solution:
This is how'd approach.
<figure>
<?php if (has_post_thumbnail()) { ?>
<?php echo wp_get_attachment_image(get_post_thumbnail_id($post->ID),
'full'); ?>
<?php } else { ?>
<img src="<?php echo get_stylesheet_directory_uri()
.'/components/assets/images/blog-placeholder.png'; ?>">
<?php } ?>
</figure>
Answer
Solution:
I would create a function which contains all of the logic, then just pass in the post ID. Add the function to your functions.php
file, and then use it in your pages.
<?php
function get_feat_image_or_default($id=false){
$path = "https://picsum.photos/800";
if($id){
$path = get_the_post_thumbnail_url(id,"large") ?: $path;
}
return $path;
}
// Then call it like this:
echo ?> <img src="<?= get_feat_image_or_default($post->ID); ?>" />
Source