Troubleshooting “Warning: Invalid argument supplied for foreach()” when traversing WordPress JSON feed

I need to retrieve tags for WordPress posts in a JSON feed script. The code below was in the original script, but it breaks if posts don’t have more than two tags and throws the warning Warning: Invalid argument supplied for foreach().

$tags = array();
foreach((get_the_tags()) as $tag) {
    $tags[] = $tag->name; 
}
$single["tags"] = $tags;

Here’s some code that I updated to get it to work if there are less than two tags, but this will cause all tags to be appended to the next post in the each. So if the first post has “tag1” and “tag2” and the second has “tag3” and “tag4”, the third post in the JSON feed will have tags such as “tag1”, “tag2”, “tag3″, tag4”, and “tag5” (even if it should just have “tag5”.

$my_tags = get_the_tags();
if ($my_tags){
    foreach($my_tags as $tag) {
        $tags[] = $tag->name; 
    }
}

Related posts

Leave a Reply

1 comment