On my custom page with pagination I have 6 pictures from the last posts, so far so good.

Have a look here: http:sayami.de

My code:

        global $wp_query;
        $paged = (get_query_var('page')) ? get_query_var('page') : 1;
       'posts_per_page' => '6',
        $count = 0;
        $wp_query->max_num_pages = 10;      
        if (have_posts()) : while (have_posts()) : the_post();
<?php $count++; //update count ?>

<div class="xxx_<?php echo $count;?>"><img src=" <?php $image = wp_get_attachment_image_src(get_post_thumbnail_id(), 'medium'); echo $image[0]; ?>" /></div>

<?php endwhile; ?>
<? endif; ?>

Now I try to get the the first image url from each page. I need the url for a small javascript outside this loop. I tried this, but the result is not the first image, but the 6th image.

     $image = wp_get_attachment_image_src(get_post_thumbnail_id(), 'medium');
     echo $image[0]

How can I get the first image url?

1 Answer 1


get_post_thumbnail_id() is going to default to using the $post global. That global is set to each post in turn as the Loop runs, so at the end of the Loop it will be set to the last post.

The easiest thing to do would be to set $image before the Loop runs, but wp_reset_query would do it too, if resetting the Loop does not through off other code on your page.

Also, you mention that you need this for Javascript. Javascript alone should be able to pick out the first URL in the markup that is already being printed by the Loop.

  • ah yes, grabbing by js is possible, but I thought it is more easy to get out of the php code, but I will give this a try, thx
    – Omar
    Jan 30, 2014 at 16:12
  • At least I have solved it with js, but anyhow, i would be interest whether their is a solution to grab the first url by php in this case, my idea was to explode the array, buti wasn't able to do this
    – Omar
    Jan 30, 2014 at 17:19

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.