說明:透過 attachment_url_to_postid
方法用 URL 網址反查 post id,最後再使用 update_post_meta 更新 _wp_attachment_image_alt
meta 即可。
$items = [
[
"alt" => "FIC digital instrument cluster adopts full LCD display.",
"url" =>
"https://www.xxxxxx/wp-content/uploads/2023/11/A-Digital-Cluster-上_1000-562.jpg",
],
];
foreach ($items as $item) {
$attachment_id = attachment_url_to_postid($item['url']);
update_post_meta($attachment_id, '_wp_attachment_image_alt', $item['alt']);
}
可能會遇到 url 包含尺寸的問題,這時候可以使用這個方法來轉換 url
function remove_image_size_from_url($image_url) {
// Define a regex pattern to match the size in the URL
$pattern = '/-\d+x\d+\./';
// Use preg_replace() to remove the matched pattern
$updated_url = preg_replace($pattern, '.', $image_url);
return $updated_url;
}
程式碼改寫為:
foreach ($items as $item) {
$url = remove_image_size_from_url($item['url']);
$attachment_id = attachment_url_to_postid($url);
if ($attachment_id) {
update_post_meta($attachment_id, '_wp_attachment_image_alt', $item['alt']);
}
}
最後驗收 alt 的方法可以瀏覽 /wp-admin/post.php?post={post_id}&action=edit