I’m trying to create a code that will show the a photo if there is featured image otherwise it will just show the page title. This code is in my header as it’s near the logo.

When I use this code on a page without a featured image:

<?php

if ( get_post_thumbnail_id() =='' ) {
   echo 'no picture';
    echo 'its id is '.get_post_thumbnail_id();
}
else {
     echo 'there is a thumbnail';
    echo 'its id is '.get_post_thumbnail_id();

}
?>

It returns “there is a thumbnail it’s id is -3.”

When I run this code on a page without a featured image:

<?php if ( has_post_thumbnail() ) :?>
  <img class="img-responsive logo-main scale-with-grid" src="<?php the_post_thumbnail_url('full'); ?>"/>
  <div class='text-box'>
   <p class='dataNumber title'><?php the_title();?> </p>
  </div>
</div>
<?php else: ?>
  <div class="logo-main scale-with-grid">no postthumb</div>
  <div class='text-box'>
   <p class='dataNumber title'><?php the_title();?> </p>
  </div>
</div>
<?php endif; ?>

IT returns this:

<div class="containerBox">
  <img class="img-responsive logo-main scale-with-grid" src="">
  <div class="text-box">
   <p class="dataNumber title">Careers </p>
  </div>
</div>

If i set a featured image both codes run fine.

Read more here: get_post_id returns a negative number


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: