In wordpress, I am using :
$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
I have tried using if($posts){}
but the notice still comes up. How do I prevent this notice other than turning off error messages in 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" is used in the query of wordpress as global and must be an array.
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.
try defining the offset in your $args ie ('offset' => 1) and instead of using the usual {} try using hooks and "endforeach;"
My foreach statements in wordpress dev are structured like:
<?php foreach($myPosts as $post) : setup_postdata($post) ?>
<?php the_title(); ?>
<?php the_content(); ?>
// etc
<?php endforeach; ?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.