duanjian7617 2014-07-20 09:33
浏览 37
已采纳

用于多个ID的Wordpress WP_Query返回null

I have following array:

array (12,15,21,32,33);

And then I use the following query to get the posts (of the above of IDs):

$the_query = new WP_Query( array("post__in"=>$ids_array) );       // edited

    while($the_query->have_posts())
    {
$the_query->the_post(); // added on edit, but still does not work      
the_title()."<br />";
    }

But I get nothing, no error and no interruption. I have checked the IDs and they are correct.

EDIT: I have put this query at the end of a module which is loaded into the footer. I don't know if it is important or not:

  • 写回答

1条回答 默认 最新

  • doudun2212 2014-07-20 09:38
    关注

    You forgot to add while ( $the_query->have_posts() ) : $the_query->the_post();.

    You are just checking to see if you have posts, but doing nothing further

    $ids_array = array (12,15,21,32,33);
    
    $the_query = new WP_Query( array('post__in'=>$ids_array) );       
    
    <?php if ( $the_query->have_posts() ) : ?>
    
      <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <h2><?php the_title(); ?></h2></br>
      <?php
         endwhile; 
        wp_reset_postdata(); 
       endif; 
      ?>
    

    EDIT

    I think the underlying problem here is not this custom query, as this custom query works. It seems from your comments that you are using another custom query on the same page.

    I don't know what the code of the first query looks like, but here are some troubleshooting points you need to go and have a look at

    • Most probably you did not reset the postdata on your first query. This will break your second query. wp_reset_postdata is extremely important when you are running custom queries with WP_Query and with get_posts. Check that you have used wp_reset_postdata after your first instance of WP_Query. Your first query should be in the same format as the one in my answer

    • You should use different variables for each instance of WP_Query. For example $variable1 = new WP_Query( YOUR ARGUMENTS ) for first instance and $variable2 = new WP_Query( YOUR ARGUMENTS ) for your second instance

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试