I am having a little trouble displaying a default image as a background image when a feature image is not present. This is the code I am using

 <?php if (has_post_thumbnail( $post->ID ) ): ?>
 <?php $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' );?>
 <?php else :
 $src = get_bloginfo( 'stylesheet_directory') . '/lib/images/home1-1024x681.jpg'; ?>
 <?php endif; ?>
 <section id="halfpro" style="background:url(<?php echo $src[0]; ?> ) no-repeat center center">

When I upload a feature image it works but when I do not have one selected the div is empty. When I look at the source it seems as though it is not rendering the URL correctly, I am getting this background:url(h ).

What am I missing?

  • Your certain $src = get_bloginfo( 'stylesheet_directory') . '/lib/images/home1-1024x681.jpg'; returns an image? That the home1-1024x681.jpg image actually exists in your wp-content/themes/your-theme/lib/images/ directory? Try using get_stylesheet_directory_uri() or get_bloginfo('template_directory') instead of get_bloginfo( 'stylesheet_directory') .
    – BODA82
    Nov 18, 2014 at 15:01
  • I am 100% sure. I tried each solutions you provided and still nothing. The problem seems to be it is not displaying the url in the source. All I am getting now is background:url(h )@BODA82 Nov 18, 2014 at 15:04

1 Answer 1


I found the solution from a Wordpress forum and this is what they used. Works perfect

 <?php if (has_post_thumbnail( $post->ID ) ): ?>
 <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), '' );
 $image = $image[0]; ?>
 <?php else :
 $image = get_bloginfo('stylesheet_directory') . '/lib/images/home1-1024x681.jpg'; ?>
 <?php endif; ?>
 <section id="halfpro" style="background-image: url('<?php echo $image; ?>')" >

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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