0

This works fine within the loop but i cannot hook it outside the loop.

global $post;
$args = array( 'post__in' => array( 1, 5, 17, 19, 21, 23, 25, 27, ) ); 
$thumbnails = get_posts($args);
foreach ( $thumbnails as $thumbnail ) {
    if ( has_post_thumbnail( $thumbnail->ID ) ) {
        echo '<a href="' . get_permalink( $thumbnail->ID ) . '" title="' . esc_attr( $thumbnail->post_title ) . '">';
        echo get_the_post_thumbnail( $thumbnail->ID, 'thumbnail' );
        echo '</a>';
    }
}

I've tried dozens of variations using get_posts and WP_Query.

Edit: Added an array of specific post I.D's

  • 1
    I don't see any reason why the posted code wouldn't work outside the loop. It works for me. Can you elaborate a little what "it doesn't work" means? What global $post does in that code? – cybmeta Feb 18 '15 at 19:48
  • Switch to WP_Query and then do echo $thumbnails->request and check what SQL query is generated from the query – Pieter Goosen Feb 19 '15 at 4:27
  • It works when using a shortcode in a widget outside the loop but not when i hook the function in directly. – Brad Dalton Feb 19 '15 at 14:12
  • Where are you trying to hook this, which hook are you using then. I suspect you have the wrong hook, one that is running to early – Pieter Goosen Feb 20 '15 at 4:26
  • Tried wp_head and loop_start. – Brad Dalton Feb 20 '15 at 6:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.