我正在尝试为 WordPress 网站创建一个基本的 PHP 函数,该函数读取来自 API 的 JSON 响应,并将每种动物的数据添加到自定义帖子中。
我在弄清楚解析 JSON 和循环动物及其各自数据的正确方法时遇到了一些麻烦。
我知道这只是我没有正确理解 JSON 结构,并且我没有以正确的方式解析它 - 所以希望有人可以指导我正确的方法。
这是我的函数 - 目前的问题是循环不起作用,我无法获取动物数据来填充字段。
<?php
//Get advertised animals from ARMS and generate custom post
function get_advertised_animals(){
$animals = [];
$results = wp_remote_retrieve_body(wp_remote_get('https://##my-test-API##'));
$results = json_decode($results);
if ( ! is_array($results) || empty ($results) ){
return false;
}
$animals[] = $results;
foreach ($animals[0]['Animals'] as $animal){
$animal_slug = sanitize_title($animal->Name . '-' . $animal->FFAR_ID)
$inserted_animal = wp_insert_post([
'post_name' => $animal_slug,
'post_title' => $animal->Name,
'post_type' => 'animal',
'post_status' => 'publish',
'post_content' => $animal->Biography,
'post_excerpt' => $animal->Blurb
]);
// Make sure we have the post id
if ( is_wp_error( $inserted_animal )) {
continue;
}
//Array of all data from the API mapped to the ACF field IDs
$fillable = [
'field_5e807346d13f2' => 'Gender',
'field_5e807363d13f3' => 'Breed',
'field_5e80736fd13f4' => 'Colour',
'field_5e807376d13f5' => 'DateOfBirth',
'field_5e807410d13fb' => 'ExtListURL',
'field_5e8b1d251e542' => 'AdoptionFee'
'field_5e807420d13fc' => 'Image1',
'field_5e8074c2d13fd' => 'image2',
'field_5e8074cad13fe' => 'Image3',
'field_5e8074d7d13ff' => 'Image4',
'field_5e8073b0d13f7' => 'activityLevel',
'field_5e8073bcd13f8' => 'GoodWithDogs',
'field_5e8073e7d13f9' => 'GoodWithCats',
'field_5e8073f7d13fa' => 'GoodwithChildren',
'field_5e8073a7d13f6' => 'Size'.
'field_5ea4e481081ed' => 'id'
];
foreach ( $fillable as $key => $name ) {
update_field ( $key, $animal->$name, $inserted_animal );
}
}
}
?>
尚方宝剑之说
繁华开满天机