我有这从URL保存为存储图像的功能,唯一的问题是这一切似乎很好地工作比其他图像“无法找到”保存图像从URL到WordPress的媒体库
图片和名称都在媒体库中,但图片被打破,因为当您通过url打开图片时,它会显示“未找到”
如果我错过了某些东西,您能否告诉我一些问题。
function set_image_from_url($url) {
$tmp = download_url($url);
$file_array = array(
'name' => basename($url),
'tmp_name' => $tmp
);
/**
* Check for download errors
* if there are error unlink the temp file name
*/
if (is_wp_error($tmp)) {
@unlink($file_array[ 'tmp_name' ]);
return $tmp;
}
/**
* now we can actually use media_handle_sideload
* we pass it the file array of the file to handle
* and the post id of the post to attach it to
* $post_id can be set to '0' to not attach it to any particular post
*/
$post_id = '0';
$id = media_handle_sideload($file_array, $post_id);
/**
* We don't want to pass something to $id
* if there were upload errors.
* So this checks for errors
*/
if (is_wp_error($id)) {
@unlink($file_array['tmp_name']);
return $id;
}
/**
* No we can get the url of the sideloaded file
* $value now contains the file url in WordPress
* $id is the attachment id
*/
$value = wp_get_attachment_url($id);
// Now you can do something with $value (or $id)
return $id;
}
如果您确实使用url请求图片的路径是正确的,您是否有'.htaccess'文件?如果是,请将其内容发布在问题中。 –
使用media_sideload_image wordpress函数 – onlinewebsite
@onlinewebsite这和我用过的media_handle_sideload函数有什么区别? – Kyon147