dpdhnd3577 2011-05-26 14:51
浏览 99
已采纳

在运行Wordpress JSON提要时对“警告:为foreach()提供的参数无效”进行故障诊断

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; 
    }
}
  • 写回答

1条回答 默认 最新

  • dougang2749 2011-05-26 14:53
    关注

    there is a function to check if it is an array, it's named is_array(), read more -> http://php.net/manual/en/function.is-array.php

    if (is_array($my_tags)){
    

    also empty that array each time you loop through a post, just by adding the code from your first example:

    $my_tags = array();
    $my_tags = get_the_tags();
    if (is_array($my_tags)){
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献