How can I show the post thumbnail from the most recent of a certain post type, in widget?
-
16-10-2019 - |
سؤال
I'm using the excellent PHP Code Widget plugin, and want to create a widget that displays the post thumbnail (aka featured image) for the most recent 'project' post. Here's the code I have so far, but it isn't producing the desired result. This actually outputs nothing.
<?php
global $post;
$args = array(
'post_type' => 'project',
'posts_per_page' => 1,
);
$thumbnails = get_posts($args);
foreach ($thumbnails as $post)
{
setup_postdata($post);
?>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'thumbnail' ); ?></a>
<?php
}
Any suggestions on what I need to change for this to work?
المحلول
Moving here so comments don't turn into a mess.
Basically there are two things that can go wrong here:
Fetching of posts. Check that
$thumbnails
gets correct post and only one. I am not sure if that is the issue, butget_posts()
docs listnumberposts
argument instead ofposts_per_page
that is listed forquery_posts()
. That might make a difference.Messing with global variables. For this usage I wouldn't touch global
$post
at all, directly or withsetup_postdata()
either. Just use non-loop versions of functions that can fetch things you need by post id -get_permalink()
andget_the_post_thumbnail()
.