Reputation: 631
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?
Upvotes: 0
Views: 93
Reputation: 96
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;
};
Upvotes: 0
Reputation: 1699
Try a ternary operator:
$html .= has_post_thumbnail() ? get_the_post_thumbnail(get_the_ID(), array('class' => 'img-responsive')) : $First_Img;
Upvotes: 1
Reputation: 982
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;
};
Upvotes: 1
Reputation: 9382
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.
Upvotes: 1