I'd like to know if there is a way to store WP_Query results in variables that I can then go ahead and insert anywhere on the page outside of the loop. For instance, say I want to get the feature image urls of three latest posts and I want to set variables in a way akin to the following.(note that the code below is for illustration purposes only as I have no idea how to parse the results from the loop for each post)

$featureImageFirst = wp_get_attachment_url();
$featureImageSecond = wp_get_attachment_url();
$featureImageThird = wp_get_attachment_url();

In response to Soren's help I did this:

Hi Soren, please have a look at my code. This is what is happening.

    // Get latest three posts
    $args = [ 
        'posts_per_page' => 3,
        'orderby'      => 'date',
        'order'    => 'DESC'

    // Fetch posts
    $query = new WP_Query( $args );

    if( $query->have_posts() )
        while ( $query->have_posts() )
            $featureImage[$current_post] = wp_get_attachment_url(     get_post_thumbnail_id() );
<div><img src="<?php echo $featureImage[0]; ?>"></div>

And this is what I get

<div><img src></div>
  • Thanks for the advice Pieter - I wasn't aware of the etiquette until now. – C. Ruben Feb 11 '16 at 22:28

From what I read, you read the URL/path to the post thumbnails is an array. We need to look at a couple of things here to make this as lean and predictable as possible


  • We do need some way to make sure that we get the latest three posts which actually have thumbnails to avoid unexpected output and bugs. It is always important to code with a mindset that my code will be hacked and it will fail and it will have bugs. Once you have that mindset, then you look at your code from a different angle, which make you to ask questions like: What if this specific poece of code returns an error, how will it affect my output, how will I handle such errors safely and reliable in an expected, predictable way without breaking something else on my site

  • We only really need the post ID's from the three latest posts, so to save resources, why not only query for post ID's

  • When you need lean, non-paginated, to the point queries like this, I always use get_posts as it breaks pagination legally. This makes your query faster, which really helps on sites with many posts. You can still use WP_Query, but then you would need to remember to pass 'no_found_rows' => true to your query arguments (which is exactly what get_posts does btw). Another plus using get_posts is that it just return the $posts property from the WP_Query instance. But this is all just personal preference


I prefer to write functions for long pieces of code to keep my templates as simple and short as poosible. I can then just call my functions where I need them or even use do_action() calls in my templates and then hook my functions to that specific action

Anyway, lets look at the function; (NOTE: The following is untested, needs PHP 5.4+ and canbe made more dynamic as needed)

function get_latest_post_thumbnails_urls()
    // Set an empty variable which will hold our array of URL's
    $output = [];

    // Set our query args
    $args = [
        'posts_per_page' => 3,
        'fields'         => 'ids', // Only get post ID's
        'meta_query'     => [ // Get posts which has thumbnails only
                'key'     => '_thumbnail_id',
                'compare' => 'EXISTS'
        // Any additional parameters you might need
    $q = get_posts( $args );

    // ALWAYS make sure we have posts, else return $output
    if ( !$q )
        return $output;

    // Ok, we have posts, lets loop through them and create an array of URL's
    foreach ( $q as $id ) 
        $output[] = wp_get_attachment_url( get_post_thumbnail_id( $id ) );

    // Return our array
    return $output;

We can now use get_latest_post_thumbnails_urls(); anywhere where we need it.


We need to remember, our function might return an empty array, or an array with 1, 2, or 3 URL's, so we must always make sure about this before we try to use anything to avoid bugs and have unexpected failures

This is a probable safe usecase we can use

$urls = get_latest_post_thumbnails_urls();
// Make sure we do not have an empty array

if ( $urls ) {
    foreach ( $urls as $url ) {
        // Do something with your thumbnail url
        echo $url . '</br>'; // For testing, remove this
| improve this answer | |
  • Pieter I tested the code just as you have it and it only outputs one url. Every post in my wordpress site has a thumbnail so there should be three. Also there is a syntax error that I fixed where thumbnail is mispelled. Will fix in post. – C. Ruben Feb 12 '16 at 22:43
  • @C.Ruben many thanks for the feedback and the bug fix. One tend to miss such simple things when coding from mobile devices ;-). I have tested my code, and it works perfectly on my side now. I have updated the last block to include a line break. If you still get only one URL back, you most probably have a bad pre_get_posts action somewhere. Add remove_all_actions( 'pre_get_posts' ); before $urls = get_latest_post_thumbnails_urls(); and test again. If it works, you need to identify where that bad action is. Do a search through your theme and plugins – Pieter Goosen Feb 13 '16 at 6:52

A) You can store the url in an array. The index of the post currently being displayed is $current_post. So you can use it also as array index.

if ( have_posts() ) : while ( have_posts() ) : the_post(); 
    if ( has_post_thumbnail() ) {
        $featureImage[$current_post] = wp_get_attachment_url( get_post_thumbnail_id() );

After the Loop you have:

$featureImage[0] (value: http://example.org/thumbnail_of_post_1.jpg)

$featureImage[1] (value: http://example.org/thumbnail_of_post_2.jpg)

$featureImage[2] (value: http://example.org/thumbnail_of_post_3.jpg)

B) You can use multiple queries on a page. See here in the Codex.

| improve this answer | |
  • Soren, Wouldn't that repeatedly set the variable to $featureImage for every wp_get_attachment_url() in the query? How would I get it to something like $featureImage1 $featureImage2, etc. @soren Regarding the multiple queries, I heard that can cause delay in page load. – C. Ruben Feb 11 '16 at 22:31
  • I edited my answer. so you have an better example. The delay is true, but just a few milliseconds. So you wont recognize it. – Sören Wrede Feb 11 '16 at 22:44
  • Please see my revised question. – C. Ruben Feb 12 '16 at 0:13

Your Answer

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

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