I want to use a fallback image if no featured image is set. I'm using the following code, but the image is not shown...

<?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?>
    <?php the_post_thumbnail( array(334, 259) ); // Declare pixel size you need inside the array ?>
<?php else : // No thumbnail? Showing default is better UX than no image. ?>
    <img src="/wp/wp-content/themes/klicknet-theme/images/testbild.png" 
alt="testbild" width="334" height="259" title="Bild: <?php the_title(); ?>"> 
<?php endif; ?>

Any ideas why?

  • It's probably something simple like the wrong URL to the image. First set your else statement to something basic like echo 'No featured image found'; so you can tell whether "else" is ever being met. If it is, then the URL to your image is wrong - unless you have your whole site installed in a "wp" folder, you probably just need to remove /wp from the very beginning of the img src. – WebElaine Jul 3 '18 at 15:17
  • no i checked it... – tom84 Jul 4 '18 at 14:26
  • Where are you running this code? Are you sure you're in the Loop so has_post_thumbnail() knows which Post you're asking about? – WebElaine Jul 5 '18 at 13:51

Your code looks OK and it should work just fine. But there are some things you can (and you should) fix.

1. You don't use absolute URL for your fallback image

You pass /wp/wp-content/themes/klicknet-theme/images/testbild.png as src of your image. It would be much better and more secure if you'd use WP functions in there. For example like so:

<img src="<?php bloginfo('template_url'); ?>/images/testbild.png">

2. You don't escape the title properly

In your fallback image you use the_title() in title attribute. But you don't escape it as an attribute. If the title contains " character, it will break your HTML. Another problem is that the title can contain HTML tags, and they will be printed in your attribute.

If you want to use title as attribute, you should use the_title_attribute function instead. So the fixed version of that line can look something like this:

<img src="<?php bloginfo('template_url'); ?>/images/testbild.png" alt="testbild" width="334" height="259" title="<?php the_title_attribute( array( 'before' => 'Bild: ', 'after' => '' ) ); ?>"> 
| improve this answer | |
  • 1
    I'd suggest using get_theme_file_uri() over bloginfo() these days. Better child theme support that way. – Jacob Peattie Jul 4 '18 at 5:53
  • thanks for your answer... but the default image is not loaded <div class="image-wrapper"> </div> the div is empty and only shows "" this.... – tom84 Jul 4 '18 at 14:19

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.