0

I get as result of a main sql an array of post IDs, now what I need that Array of ids post to obtain the information and be presented in the following way:

<?php
    $ids = [1,2,3,4,5];
    // Here is some execution or process
    // then I need to present the post as a normal loop
    if (  have_posts()  ) :
      while ( have_posts() ) : the_post();
          echo get_the_title();

      endwhile; 

     endif;
     wp_reset_query();

How can I run the ids and then display it in a loop?

0

1 Answer 1

2

If I understand it properly,

You can use the post__in parameter to query for specific posts where the post ID is in that parameter:

$ids = [ 1, 2, 3, 4, 5 ];
$query = new WP_Query( array(
    'post__in' => $ids,
    // ... other args, if any.
) );

// Then loop through the posts.
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) : $query->the_post();
        the_title();
        // ... your code here.
    endwhile;
    wp_reset_postdata();
}

Alternatively, use foreach with setup_postdata() without having to do the new WP_Query():

global $post;
$ids = [ 1, 2, 3, 4, 5 ];
foreach ( $ids as $id ) {
    $post = get_post( $id );
    setup_postdata( $post );

    the_title();
    // ... your code here.
}
wp_reset_postdata();
0

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.