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.

global $post;
$args = array(
    'post_type' => 'project',
    'posts_per_page' => 1,
$thumbnails = get_posts($args);
foreach ($thumbnails as $post)
        <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'thumbnail' ); ?></a>

Any suggestions on what I need to change for this to work?

  • 3
    Nothing like not even empty markup for link tag? Had you checked that post is returned at all and $thumbnails is not empty?
    – Rarst
    Commented Dec 8, 2010 at 20:08
  • Correct, nothing at all. What is the best way to check $thumbnails? If I use "print_r($thumbnails);", I get "Array ( )" as the output. Commented Dec 8, 2010 at 20:30
  • Turns out I wasn't using the correct slug for the post type. It should have been 'projects'. Thanks for the suggestion to check $thumbnails, that's what got me thinking about why it was empty. It works now, except I get three featured images, instead of the 1 I expected. Any thoughts? Commented Dec 8, 2010 at 20:34

1 Answer 1


Moving here so comments don't turn into a mess.

Basically there are two things that can go wrong here:

  1. Fetching of posts. Check that $thumbnails gets correct post and only one. I am not sure if that is the issue, but get_posts() docs list numberposts argument instead of posts_per_page that is listed for query_posts(). That might make a difference.

  2. Messing with global variables. For this usage I wouldn't touch global $post at all, directly or with setup_postdata() either. Just use non-loop versions of functions that can fetch things you need by post id - get_permalink() and get_the_post_thumbnail().

  • Using numberposts did indeed fix it. Interesting, since the Codex says that get_posts() "can also take the parameters that query_posts() can". I think I understand #2 - I'll see if I can successfully re-write it and come back if that doesn't work out. Thanks for the help! Commented Dec 8, 2010 at 22:02
  • Yeah, most of the time query_posts() and get_posts() are identical. But they do have some differences in internals and default arguments, so I try to stick with what docs say when arguments do seemingly same thing.
    – Rarst
    Commented Dec 8, 2010 at 22:06
  • Just FYI, looks like this has been fixed: core.trac.wordpress.org/ticket/15150 Commented Dec 8, 2010 at 22:53

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.