简体   繁体   English

使用get_post()时如何在wordpress的query.php中处理未定义的偏移量0

[英]How to address undefined offset 0 in wordpress's query.php when using get_post()

In wordpress, I am using : 在wordpress中,我正在使用:

$posts=get_posts($args)
foreach($posts as $post){
   //do stuff
} 

However, when there is no posts I get 但是,当我没有帖子时

undefined offset: 0 in C:\\xampp\\htdocs\\wrDTC\\wp-includes\\query.php on line 2859 未定义的偏移量:在第2859行的C:\\ xampp \\ htdocs \\ wrDTC \\ wp-includes \\ query.php中为0

I have tried using if($posts){} but the notice still comes up. 我尝试使用if($posts){}但是通知仍然出现了。 How do I prevent this notice other than turning off error messages in php? 除了关闭php中的错误消息之外,我该如何阻止此通知?

use Something like this... 使用像这样的东西......

  if(!empty($args) && count($args)>0){
    $posts=get_posts($args)
    foreach($posts as $post){
       //do stuff
    } 
    }

You can't simply use the $posts as name of vars in the loop. 您不能简单地使用$ posts作为循环中变量的名称。

"$posts" is used in the query of wordpress as global and must be an array. “$ posts”在wordpress查询中用作全局,必须是数组。

If you choose to name you var $posts, this result into an undefined offset 0 because your $posts do not have offset 0. remember, you just reset it. 如果您选择为var $ posts命名,则此结果为未定义的偏移0,因为您的$ posts没有偏移0.记住,您只需重置它。

try defining the offset in your $args ie ('offset' => 1) and instead of using the usual {} try using hooks and "endforeach;" 尝试在$ args中定义偏移量('offset'=> 1),而不是使用通常的{}尝试使用钩子和“endforeach;”

My foreach statements in wordpress dev are structured like: 我在wordpress dev中的foreach语句结构如下:

<?php foreach($myPosts as $post) : setup_postdata($post) ?>

      <?php the_title(); ?>
      <?php the_content(); ?>
      // etc
      <?php endforeach; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM