最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

loop - Array ids post to function have_post

programmeradmin2浏览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?

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 0
Add a comment  | 

1 Answer 1

Reset to default 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)

  1. 暂无评论