0

I am new to PHP and I'm unable to solve the code. It's showing an error.

<?php 

function thumbImg() {
   if ( has_post_thumbnail() ) {
       the_post_thumbnail( array(54,54) );
   } else {
       <img src='<?php echo $data['featured_img']; ?>' alt='<?php the_title(); ?>' /> 
   }
} 

?>

What I am trying to achieve is that set a fallback image for a recent post widget if there is no featured image set, so I am trying to make a function/shortcode I can use in the my recent post widget page ['featured_img'] which will get data from admin panel.

1
  • You need to close php tag before start to show html or put html code inside a string and use echo. This is basic php. (look at your else statement)
    – Sisir
    Jan 29, 2016 at 8:24

2 Answers 2

1

You are mixing html and php content. You should write it like this:

<?php 

function thumbImg() {
   if ( has_post_thumbnail() ) {
       the_post_thumbnail( array(54,54) );
   } else {
       echo "<img src='{$data['featured_img']}' alt='".get_the_title()."' />";
   }
} 

?>

This way, you don't need to open and close again the php tag.

1
  • 1
    should use get_the_title()
    – Sisir
    Jan 29, 2016 at 8:33
0

You need to close the PHP tag before you write html code for image source and then reopen the PHP tag once your HTML is finished.

    <?php 

function thumbImg() {
   if ( has_post_thumbnail() ) {
       the_post_thumbnail( array(54,54) );
   } else {
    ?>
       <img src='<?php echo $data['featured_img']; ?>' alt='<?php the_title(); ?>' />
       <?php
   }
} 

?>

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