I am storing data from an API in a custom post type made up with Advanced Custom Field. The API returns image urls, where each is given a text field in Advanced Custom Field. I'd like to set a specific of those as the featured image of the post type.
I found a few ways of doing it, if the image was a imagefield or galleryfield, but since it's just a URL for now, I am struggling with it.
So the question is boiled down to; how would I set a featured image from a given URL from a 3rd party?
Any advice would be appreciated.
Some code from functions.php
// Setting Costum Post Type
add_action('init', 'register_cars');
function register_cars(){
register_post_type('car', [
'label' => 'Cars',
'public' => true,
'capability_type' => 'post',
'publicly_queryable' => true,
'show_ui' => true,
'hierarchical' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'car', 'with_front' => false),
'supports' => array('title', 'editor', 'thumbnail'),
'menu_position' => 31
]);
}
// Getting the cars from our API
function get_cars_from_api() {
// Call the API and get a response
$url = "URL_HERE";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"Authorization: Basic AUTH_HERE",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// For debug
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
// Decode our response to json
$resp = curl_exec($curl);
curl_close($curl);
$arr = json_decode($resp, true);
$cars[] = $arr;
// Loop through our response
foreach($arr['Vehicles'] as $car) {
$car_slug = sanitize_title($car['Make'] . ' ' . $car['Model'] . ' ' . $car['Variant'] . ' (ID: ' . $car['VehicleId'] . ')');
$car_name = $car['Make'] . ' ' . $car['Model'] . ' ' . $car['Variant'] . ' (ID: ' . $car['VehicleId'] . ')';
$existing_car = get_page_by_path($car_slug, 'OBJECT', 'car');
// Check if we need to create or update the car
if($existing_car === null) {
$inserted_car = wp_insert_post([
'post_name' => $car_slug,
'post_title' => $car_name,
'post_type' => 'car',
'post_status' => 'publish'
]);
if(is_wp_error($inserted_car)) {
continue;
}
$fillable = [
...
'field_61f2d2e5131b1' => $car['Pictures'][0],
...
];
foreach($fillable as $key => $name) {
update_field($key, $name, $inserted_car);
};
} else {
$existing_car_id = $existing_car->ID;
$existing_car_timestamp = get_field('ModifiedDate', $existing_car_id);
if($car['ModifiedDate'] >= $existing_car_timestamp){
$fillable = [
...
'field_61f2d2e5131b1' => $car['Pictures'][0],
...
];
foreach($fillable as $key => $name) {
update_field($key, $name, $existing_car_id);
};
}
}
}
print_r('You can now close this page. Your cars are updated');
}
add_shortcode('get_cars_from_api', 'get_cars_from_api');