gpt4 book ai didi

php - wp_generate_attachment_metadata 返回一个空数组

转载 作者:可可西里 更新时间:2023-10-31 23:31:22 27 4
gpt4 key购买 nike

我正在编写一个 Wordpress 插件来下载我博客上的远程图像。

我做了一个在本地上传远程图片的功能,然后返回它的ID。除了

    $attach_data = wp_generate_attachment_metadata( $attach_id, $local_file );

返回一个空数组 - 它不应该。

wp_generate_attachment_metadata其中,负责生成上传图像的缩略图。但是我在运行代码时没有创建缩略图。

我检查了我发送给函数的值,它们似乎是正确的:我有一个 ID 和一个上传文件的绝对路径,如法典中所述。尽管如此,我还是无法让我的代码正常工作:

$attach_data 不应为空...

有人能帮忙吗?

function upload_from_remote_url($url,$post_id){

$url = $this->validate_remote_media_url($url); //check file is not on local server
if (!$url) return false;

if ($existing_id = $this->media_already_exists($url)) return $existing_id; //url already has been downloaded

$upload_dir = wp_upload_dir();
$wp_mime_types = wp_get_mime_types();

//fetch image
$response = wp_remote_get( $url );

//get filename without extension
$filename = basename( $url ); //get filename & extension
$filename_strip = preg_replace('/\.[^.]*$/', '', $filename); //strip extension

//get extension from content type,
//because wp_upload_bits needs an extension and certain url don't have one.

$file_type = wp_remote_retrieve_header( $response, 'content-type' );
$extensions = array_search($file_type,$wp_mime_types);
$extensions_arr = explode('|',$extensions);
$extension = $extensions_arr[0];

$new_filename = $filename_strip.'.'.$extension; //full name
$new_filename = wp_unique_filename($upload_dir['path'], $new_filename); // be sure this name do not exist already

$uploaded = wp_upload_bits($new_filename, '', wp_remote_retrieve_body( $response ) );
if ($uploaded['error']) return false;

$local_file = $uploaded['file'];
$local_filename = basename($local_file);
$local_filetype = wp_check_filetype( $local_filename, null );

//Attachment options
$attachment = array(
'post_title'=> $local_filename,
'post_mime_type' => $local_filetype,
'post_status' => 'inherit'
);

// Add the image to your media library
$attach_id = wp_insert_attachment( $attachment, $local_file, $post_id );

if (!$attach_id) return false;

$attach_data = wp_generate_attachment_metadata( $attach_id, $local_file );

wp_update_attachment_metadata( $attach_id, $attach_data );

//save source link so we do not import several times the same media
update_post_meta($attach_id, 'grm_source', $url);

return $attach_id;

}

顺便说一句,如果任何 WP gourou 对这段代码有任何看法......我会很乐意阅读它,因为关于上传文件的 WP 文档有点乱。我在这里需要一些特定的东西,因为能够检索文件扩展名。我结束了这个,但也许你有更好的主意!

最佳答案

我遇到过类似的问题,缺少 MIME 类型。因为我只使用一种 mime 类型,所以它被修复了

'post_mime_type' => 'image/jpeg'

在那之后,它仍然没有更新元数据,但是用“wp_update_attachment_metadata”强制更新解决了问题:

$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
wp_update_attachment_metadata($attach_id, $attach_data);

关于php - wp_generate_attachment_metadata 返回一个空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21008141/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com