1
votes

I'm new to php. Developing a WordPress site.

I'd like to pull in a featured image to use as a hero background image on each post/page. If there isn't a featured image, I'd like to use a default image.

I've found working code to do each of the above individually, but not sure how to combine them.

Featured image as background image:

<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
<div id="post" class="hero-image" style="background-image: url('<?php echo $thumb['0'];?>')">
</div>

Fallback default image:

    <?php if ( has_post_thumbnail() ) {
    the_post_thumbnail( 'full' );
} else { ?>
<img src="<?php bloginfo('template_directory'); ?>/img/default-img.jpg" alt="<?php the_title(); ?>" />
<?php } ?>

Edit: this is how I did it:

<?php if ( has_post_thumbnail() ) { ?>
    <?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
    <div class="hero-image" style="background-image: url('<?php echo $thumb['0'];?>')"></div>
<?php } else { ?>
    <div class="hero-image" style="background-image: url('<?php bloginfo('template_directory'); ?>/img/default-img.jpg') "></div>
<?php } ?>
2

2 Answers

0
votes

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>
0
votes

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); ?>" />