Warning is " Invalid argument supplied for 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...
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:
$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:
$tags = get_the_tags();
if ($tags) {
foreach ($tags as $tag) {
...
}
}
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.