使用WordPress,在同一页面上两次调用一个函数第二次失败


Using WordPress, calling a function twice on same page fails second time

我在主题的function.php文件中有一个函数,它调用Edmunds API并检索库存车辆图像。

在页面模板中,如果我多次调用该函数,它将在第二次调用时失败。它第一次运行得很好,但第二次没有输出任何内容。当我尝试打印$aVehImage数组时,它是空的。(我已经验证了图像在API中可用于二次呼叫中的车辆,btw)

以下代码:

function get_edmunds_image($vehicleMake, $vehicleModel, $vehicleYear) {
    $getVehicleStyle = 'https://api.edmunds.com/api/vehicle/v2/'.$vehicleMake.'/'.$vehicleModel.'/'.$vehicleYear.'/styles?state=used&fmt=json&api_key=XXX';
    $vehicleStyleID = json_decode(file_get_contents($getVehicleStyle), true);
    $getImages = 'https://api.edmunds.com/v1/api/vehiclephoto/service/findphotosbystyleid?styleId='.$vehicleStyleID['styles'][0]['id'].'&fmt=json&api_key=XXX';
    $aImages = json_decode(file_get_contents($getImages), true);
    $aVehImage = array();
    foreach ($aImages as $image) {
        $iURL = 'http://media.ed.edmunds-media.com'.str_replace('dam/photo','',$image['id']).'_';
        array_push($aVehImage, $iURL);
    }
echo '<img src="'.$aVehImage[0].'500.jpg" />';
}

谢谢Marcos!事实上,这似乎确实是问题所在。目前,我只是使用sleep()函数暂停它一秒钟,直到找到更好的解决方案。