NickL
NickL

Reputation: 3

Wordpress featured image with fallback as a background image

Its my first foray into Wordpress and I'm trying to create a single post page. I've got the Featured image pulling in, but I'm trying to swap it out for a fallback image if there isn't a featured image.

Currently looks like this (obvs inside the loop):

<?php $thumb = get_the_post_thumbnail_url(); ?>

<div class="news-hero" style="background-image: url('<?php echo $thumb;?>')">
     <div class="page-title"><h1><?php the_title(); ?></h1></div>
</div>

Which is great as it pulls the url in which I then place with the echo $thumb bit.

I think I need to somehow define $thumb as either the thumbnail url or another URL but not sure how?

I've managed to do it as an image tag for the listing page, but would prefer to be able to do it as a background image (just pulling in URLs) if I could.

This is what the listing uses at the moment - but only works in an img tag.

<div class="news-collation-img">
    <?php if ( has_post_thumbnail() ) {
          the_post_thumbnail();
          } else { ?>
          <img src="<?php bloginfo('template_directory'); ?>/img/news/fallback-image.jpg" alt="<?php the_title(); ?>" />
    <?php } ?>
</div>

Designing pretty pictures is much easier than making it work :-p

Thanks for any help anyone can give.

Upvotes: 0

Views: 778

Answers (2)

NickL
NickL

Reputation: 3

For some reason, the above produces the template directory as plain text on the page. If I echo $thumb = bloginfo('template_directory').'/img/news/fallback-image.jpg'; it'll bring up the correct URL.

However when called back as a URL in the background image <div class="news-hero" style="background-image: url('<?php echo $thumb;?>')"> It wasn;t working.

When I changed $thumb = bloginfo('template_directory') to $thumb = get_template_directory_uri() it all works. No idea why as I'm lead to believe they do the same thing. (bloginfo('template_directory') just then executes get_template_directory_uri).

But it worked, so I'm fine with that...

Upvotes: 0

Balwant
Balwant

Reputation: 755

try this :

<?php 
//define fallback image path
$thumb = bloginfo('template_directory').'/img/news/fallback-image.jpg';
if ( has_post_thumbnail() ) {  
//override  fallback image if post has any thumbnail
$thumb = get_the_post_thumbnail_url();
 }
 ?>

<div class="news-hero" style="background-image: url('<?php echo $thumb;?>')">
     <div class="page-title"><h1><?php the_title(); ?></h1></div>
</div>

Upvotes: 0

Related Questions