Att. category and Att. Tag usage of Media Library via REST API
-
I use Media Library Assistant for quite a while now in my site and really appreciate it’s usage and richness of funtionality. Great job and many thanks!
Recently I tried to programmatically upload images and control their metadata with my own script. I am successful with almost everything, except the attachment_category and the attachment_tag. I am not able to populate the uploaded image with it’s Category or Tags. The parameters seem silently be ignored. Is there any special way how taxonomy fields are handled? Is there any internal logic to manage categories and tags? Below I have attached code snippets. Maybe you see the issue immediately.
// Update image metadata and link to the post
if ($thumbnail_id) {
$metadata_payload = [
'title' => $wpfields[11] . ' ' . $formatted_date,
'slug' => $wpfields[3],
'caption' => $wpfields[11],
'description' => $wpfields[11] . ' ' . $formatted_date,
'alt_text' => $wpfields[12],
'date' => $wpdate,
'post' => $post_id, // Link image to the post
'attachment_category' => [65], // Existing Attachment Category
'attachment_tag' => [583, 584], // Existing Tags
];
console_log("Metadata Payload: ", true);
console_log($metadata_payload, true);
$metadata_result = update_image_metadata($thumbnail_id, $wpenv . '/wp-json/wp/v2/media/', $wpuser, $wppass, $metadata_payload);
if ($metadata_result['success']) {
console_log("Metadata updated successfully for image ID {$thumbnail_id}.");
echo "<div class='alert alert-success'>Metadata updated successfully for image ID {$thumbnail_id}.</div>";
} else {
console_log("Metadata Update Failed: ", true);
console_log($metadata_result['error'], true);
exit("<div class='alert alert-danger'>Metadata update failed: " . print_r($metadata_result['error'], true) . "</div>");
}
}
......
// Update metadata for an uploaded image
function update_image_metadata($image_id, $endpoint, $wpuser, $wppass, $metadata) {
$args = [
'body' => json_encode($metadata),
'method' => 'POST',
'headers' => [
'Authorization' => 'Basic ' . base64_encode($wpuser . ':' . $wppass),
'Content-Type' => 'application/json',
],
];
$url = $endpoint . $image_id;
$response = wp_remote_request($url, $args);
$body = wp_remote_retrieve_body($response);
$data = json_decode($body);
if (isset($data->id)) {
// Return success as boolean or the metadata response for handling in the main flow
return ['success' => true, 'data' => $data];
} else {
// Return failure response
return ['success' => false, 'error' => $data];
}
}
- You must be logged in to reply to this topic.