Using WordPress, calling a function twice on same

2019-08-21 12:54发布

问题:

I have a function in my theme's function.php file that calls to the Edmunds API and retreives a stock vehicle image.

From a page template, if I call the function more than once, it fails on the second call. It works perfectly the first time, but doesn't output anything the second time. When I try and print_r the $aVehImage array, it's empty. (I've verified that images are available in the API for the vehicles in the secondary calls, btw)

Code below:

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" />';

}

回答1:

Thanks Marcos! That did, indeed, appear to be the issue. For now, I just used the sleep() function to pause it for a second, until I find a better solution.