NickMcB
NickMcB

Reputation: 927

Creating Custom Latest Post Shortcode Including Featured image

Im trying to create a custom shortcode which can be used to display the latest post, it should show the featured image for the post and the title for the post and all be wrapped in a link to the relevant article.

I have this code:

function latest_post_shortcode($atts){
$q = new WP_Query(
array( 'orderby' => 'date', 'posts_per_page' => '1')
);

$list = '<div class="latest-post">';

while($q->have_posts()) : $q->the_post();

$list = '<a href="' . get_permalink() . '">' . the_post_thumbnail('latest-post', array('class' => 'img-responsive')) . '<br />' . get_the_title() .  '</a>';

endwhile;

wp_reset_query();

return $list . '</div>';

}

add_shortcode('latest-post', 'latest_post_shortcode');

I have managed to use this code to diplay the featured image but it is being moved from within the tag and placed at the top of my Wordpress page.

Can anyone update my code or show me a better way of creating this result?

Thanks Nick

Upvotes: 1

Views: 147

Answers (2)

Bakabaka
Bakabaka

Reputation: 1505

If you use get_the_post_thumbnail() instead of the_post_thumbnail(), things should work as you want them to.

Upvotes: 2

prakhar19
prakhar19

Reputation: 473

Its because you are replacing the contents of $list variable.

You need to add them. So, use $list = $list + [Something] instead of $list = [Something]

Upvotes: -1

Related Questions