I am new to PHP, and I wanted to create a code where the thumbnail of the newest post and the post title get displayed. Both the title and the image should be inside a <a href="#">
, so that people can view the article by clicking on the image. But when I run the following PHP code the code gets printed out like this:
<img width="462" height="260" src="http://vocaloid.de/wp-content/uploads/2014/11/1920x1080_PC_a.jpg" class="attachment-735x260 wp-post-image" alt="1920x1080_PC_a"><a href="http://vocaloid.de/news/test-nr-2/"><h2>HATSUNE MIKU: PROJECT DIVA F EXTEND ANGEKÃNDG</h2></a>
Here is the original code I used:
<?php
$args = array('numberposts' => '1' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<a href="' . get_permalink($recent["ID"]) . '">' . the_post_thumbnail($recent['ID'], array(735,260)); the_title( '<h2>', '</h2>' ); '</a>';
}
?>
Try this:
Let me know the output.
Rohil_PHPBeginner’s answer is correct, however I don’t think it explains why it occurred.
Where you use
the_post_thumbnail()
, it echos the result and does not return it. It is for this reason it appears in the wrong place when you try to concatenate it into a string.If you would like to get the post thumbnail you can use
get_the_post_thumbnail()
Thus using
get_the_post_thumbnail()
you snippet would end up looking like:I hope this gives further clarity.