2

Given an array of Post objects, how might one initialize The Loop so that the common Loop functions could be used:

$posts = array( /* WP_Post, WP_Post, ... */);

while ( have_posts() ) {
    the_post();
    the_title();
}

I am aware that I could simply loop over the array elements and pass to each function the ID of each element, however for reasons beyond my control using the actual Wordpress Loop is preferred here.

The array is provided from a function that I cannot alter. For purposes of discussion it might as well have come from unserialize().

2

I'm using this in one of my custom widgets:

global $post;
$posts = array( /* WP_Post, WP_Post, ... */);
while (list($i, $post) = each($posts)) :
    setup_postdata($post);
    // use the template tags below here
    if(has_post_thumbnail()):
        ?><div class="featured_image_wrap"><?php
            the_post_thumbnail();
        ?></div><?php
    endif;
    the_title();
endwhile;
// don't forget to restore the main queried object after the loop!
wp_reset_postdata();
1
  • The key is setup_postdata($post), but note that the global $post variable should be set as well as many hooks and template tags rely on it. In DrLightman's code this is implicit as the iterator also uses the identifier $post.
    – dotancohen
    Nov 21 '16 at 7:23
0

You need to change the whole clause.

 while ( $posts->have_posts() ) {
     the_post();
     the_title();
 }

BUT, it can't work because this one is good if $posts comes from a new WP_Query().

To loop through the $posts array, you can do as follow

  foreach($posts as $post){
         echo $post->post_title;
         if($post->ID != 123){
              echo $post->post_content;
         }

  }

You write that you can have control on the query, search in the source code of the plugin for apply_filters , maybe there a way to filter these datas.

Hope it helps !

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.