0

I have created a code to get an existing post's thumbnail and echo the url, but I would like to be able to have it get a default url is the post doesn't have a set thumbnail.

Any help would be appreciated! Here's my code so far

    <?php
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id,'thumbnail', false);
?>

<div class="content" style="background-image:url(<?php echo $thumb_url[0]; ?>);">

Default Thumbnail url : http://www.website.com/img/default.jpg

1 Answer 1

1

Just set up a condition to check that thumb_id isn't empty. If it is, use your alternative image. Pretty simple stuff.

    <?php
$thumb_id = get_post_thumbnail_id();

if ( $thumb_id ) {
$thumb_url = wp_get_attachment_image_src($thumb_id,'thumbnail', false);
$thumb_url = $thumb_url[0];
} else {
$thumb_url = 'http://www.website.com/img/default.jpg';
}
?>

<div class="content" style="background-image:url(<?php echo $thumb_url; ?>);">
2
  • It's what I thought, but while it works if there's a thumb, it doesn't echo the url if there isn't
    – user51030
    Commented Jun 23, 2014 at 18:52
  • Oops - I've edited my answer.
    – vancoder
    Commented Jun 23, 2014 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.