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?
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?
Share Improve this question asked May 24, 2019 at 2:19 LΞИIИLΞИIИ 1947 bronze badges 01 Answer
Reset to default 2If 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();