1

I have a mostly normal WP_Query (getting 3 post types) for use on a Blog page. This works great.

Client wants the Instagram images to be included and ordered by date. I have all the instagram code setup and working fine creating an separate array. The caveat is that I need to format this Instagram posts array into an array with similar keys for fields like published.

I would like to Merge these arrays and use the WP Loop to output. seems like a stretch but figured I would ask.

2

Technically you can merge things into loop, by manipulating its posts field (such as $wp_query->posts for main query). WP has it in public for visibility and access, as it tends to.

However it's not that common technique, less so if you are considering injecting something that is not actually posts.

It is more common for such output to check and output additional data within the loop iterations. The most typical example is accessing $wp_query->current_post counter to do things like "output after every third post". But it's up to you really what to check and what logic to incorporate.

| improve this answer | |
  • I may look at injecting the 2nd array into the posts. There will only ever be like 20 of them for now so its not that many to add to the posts array. – TJ Sherrill May 9 '16 at 20:27
0

You don't have to merge the arrays to use them together in a loop. You just need a similar key that you can use as a hash lookup. That's where wp_list_pluck comes in handy.

// Image Data
$instagrams = array (
    array (
        'post_id' => 1,
        'image' => 'http://placekitten.com/200/300',
    ), array (
        'post_id' => 2,
        'image' => 'http://placekitten.com/200/300',
    ), array (
        'post_id' => 3,
        'image' => 'http://placekitten.com/200/300',
    ),
);

// Transform the array where post_id is the key
$hash = wp_list_pluck( $instagrams, 'image', 'post_id' );

// WP_Query arguments
$args = array (
    'post_type' => array ( 'post' ),
    'post_status' => array ( 'publish' ),
    'posts_per_page' => '3',
);

// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
    while( $query->have_posts() ) {
        $query->the_post();

        // the ID from the post
        $post_id = get_the_ID();

        // becomes the key to the image array
        if ( isset( $hash[ $post_id ] ) ) {

            $image = $hash[ $post_id ];

            echo $image;
        }
    }
}

wp_reset_postdata();

Other techniques include using an array for the loop with get_posts, custom sort with usort or reusing loops with rewind_posts -- just depends on how clever you want to be.

| improve this answer | |

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.