[英]I am developing a wordpress theme and there is a warning. How to resolve this
Warning is " Invalid argument supplied for foreach() "警告是“为 foreach() 提供的参数无效”
<?php
$tags = get_the_tags();
foreach($tags as $tag):?>
<a href="<?php echo get_tag_link($tag->term_id);?>" class="badge badge-success">
<?php echo $tag->name;?>
</a>
<?php endforeach;?>
Check if your $tags variable is an actual array of elements before trying to loop through it all...在尝试遍历所有元素之前检查您的 $tags 变量是否是实际的元素数组...
ie: IE:
<?php
$tags = get_the_tags(array('hide_empty' => false)); // show all tags, even empty 1s
// debug - uncomment below to view output
/*
echo "<pre>";
print_r($tags);
echo "</pre>";
*/
if( is_array($tags) )
{
foreach($tags as $tag):
?>
<a href="<?php echo get_tag_link($tag->term_id);?>" class="badge badge-success">
<?php echo $tag->name;?>
</a>
<?php
endforeach;
}else{
echo "<p>Not an Array!</p>";
}
?>
In general, don't assume that a variable returned from a function will always be an array, you can check this before calling foreach
like this:通常,不要假设从 function 返回的变量总是一个数组,您可以在调用foreach
之前检查这一点,如下所示:
$tags = get_the_tags();
if (is_array($tags) || is_object($tags)) {
foreach ($tags as $tag) {
...
}
}
In the specific case of get_the_tags()
, this might be enough though:在get_the_tags()
的特定情况下,这可能就足够了:
$tags = get_the_tags();
if ($tags) {
foreach ($tags as $tag) {
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.