0

i have this code below it is the loop for get popular posts in wordpress

$First_Img = '<img src="'.YPE_Catch_First_Image().'">';
while ( $popular->have_posts() ) : $popular->the_post();
    $html  = '<article>';
    $html .= '<section class="bootstrap-nav-thumb">';
    $html .= '<p>';
    $html .= '<a href="' . get_permalink() . '">';
    $html .= get_the_post_thumbnail(get_the_ID(), array('class' => 'img-responsive'));
    $html .= '</a>';
    $html .= '</p>';
    $html .= '</section>';

    $html .= '<aside class="bootstrap-title-info">';
    $html .= '<p>';
    $html .= '<a href="' . get_permalink() . '">'.get_the_title().'</a>';
    $html .= '</p>';
    $html .= '<p class="text-muted">' . get_the_date() . '||'. getPostViews(get_the_ID()) . '</p>';
    $html .= '</aside>';
    $html .= '</article>';
    echo $html;
endwhile;

i want use this code

html .= if(has_post_thumbnail()) { 
    echo get_the_post_thumbnail(get_the_ID(), array('class' => 'img-responsive'));
} else {
    echo $First_Img;
};

instead of this code

$html .= get_the_post_thumbnail(get_the_ID(), array('class' => 'img-responsive'));

but the server show the error unexpected 'if' (T-IF) please help me how i can use the conditional statement when i has post thumbnail print it and if don't has post thumbnail print the first image?

4 Answers 4

1

Incorrect:

$html .= if(has_post_thumbnail()) { 
    echo get_the_post_thumbnail(get_the_ID(), array('class' => 'img-responsive'));
} else {
    echo $First_Img;
};

Correct:

if(has_post_thumbnail()) { 
    $html .=  get_the_post_thumbnail(get_the_ID(), array('class' => 'img-responsive'));
} else {
    $html .=  $First_Img;
};
Sign up to request clarification or add additional context in comments.

Comments

1

Try this instead:

if(has_post_thumbnail()) { 
    $html .= get_the_post_thumbnail(get_the_ID(), array('class' => 'img-responsive'));
} else {
    $html .= $First_Img;
};

The .= operator essentially means "append to". The line of code you originally had meant "append whatever get_the_post_thumbnail(...) returns to $html".

This way, you check your condition with the if statement, and append what you want.

1 Comment

html should be $html
1

Try a ternary operator:

   $html .= has_post_thumbnail() ?  get_the_post_thumbnail(get_the_ID(), array('class' => 'img-responsive')) : $First_Img;

Comments

0

You should do it like this:

if(has_post_thumbnail()) { 
  $html .= get_the_post_thumbnail(get_the_ID(), array('class' => 'img-responsive'));
} else {
  $html .= $First_Img;
};

1 Comment

html should be $html

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.