【问题标题】:Need help creating posts with wp_instert_post from JSON需要帮助使用来自 JSON 的 wp_insert_post 创建帖子
【发布时间】:2017-03-20 19:17:36
【问题描述】:

我正在尝试使用 wp_insert_post 将 JSON 插入 wordpress。我撞到了一堵砖墙。我的代码和我的一些 json 可以在下面看到。

PHP:

<?php
$json_feed = "http://localhost/sample/ss-posts.json";
$json = file_get_contents($json_feed);
$obj = json_decode($json, true);

foreach($obj as $article_array){
    $url = $article_array['url'];
    $title = $article_array['title'];
    $category = $article_array['category'];
    $large_summary = $article_array['wp_post_content'];

    $post = array(
        'post_title' => $title,
        'post_content' => $large_summary,
        'post_status' => 'publish',
        'post_type' => 'post',
        'comment_status' => 'closed',
        'post_template' => 'content.php'
        );

    wp_insert_post ($post, $wp_error);
}
?>

JSON数据:

{
    "post":[
        {
            "title":"Choir to College to Commercial",
            "wp_post_title":"Choir to College to Commercial",
            "wp_post_content":"My entry into the world of music..."
        },
        {
            "title":"How to Master Vocal Technique",
            "wp_post_title":"How to Master Vocal Technique",
            "wp_post_content":"Acquiring command over vocal technique is like ..."
        },
        {
            "title":"How Do You Evaluate Singers?",
            "wp_post_title":"How Do You Evaluate Singers?",
            "wp_post_content":"Many lovers of singing say that they can't put to words ..."
        }
    ]
}

错误:运行此代码时,我收到以下“警告:在第 6 行的 /Users/andrew/Desktop/newtest.php 中为 foreach() 提供的参数无效”。

添加foreach((array)$obj as $article_array){...}时没有错误

if (is_object($obj)){...} 语句中包装整个 foreach 循环时也没有错误。

任何帮助或建议将不胜感激。提前致谢!

【问题讨论】:

  • file_get_contents() 真的返回有效的 json 吗?
  • 您在 obj 中缺少一级“post”,如 json 中所示。所以如果你只做 $obj = json_decode($json, true)['post']; 它应该可以工作
  • 在将 [post] 添加到 $obj && foreach 之后,我们现在回到原来的警告响应:Warning: Invalid argument provided for foreach() in /Users/andrew/Desktop/newtest.php 在线6

标签: php json wordpress


【解决方案1】:

由于 JSON 对象的结构是 { "post":[ {}, {}, ... ] },因此使用 json_decode 的结果将是 $obj['post'][ Array, Array, ... ]。因此,在foreach 循环中,您必须遍历$obj['post'] 数组而不是$obj

所以 foreach 必须是:

...
foreach($obj['post'] as $article_array){
...

【讨论】:

  • 在将 [post] 添加到 $obj && foreach 之后,我们现在回到原来的警告响应:Warning: Invalid argument provided for foreach() in /Users/andrew/Desktop/newtest.php on line 6
  • 等等,你的意思是你在两个地方都添加了['post']?一次在foreach,一次在json_decode,如上面评论中提到的那样?您应该只在其中一个地方添加它
  • 是的,使用其中一种方法,而不是同时使用两种方法:)
  • @nikos.svnk 请解释为什么这可以解决问题。
  • @Jack A. - 你来了 :)
猜你喜欢
  • 2014-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
相关资源
最近更新 更多