WP_GENERATE_ATTACHATION_METADATA给我一个空数组

时间:2012-04-24 作者:Klian

我有一个自定义的post类型和一个带有文件输入的metabox。

我可以插入附件,但我无法更新附件元数据,我不知道如何修复它,因为我没有收到任何错误。

这是我的代码:

$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id,  $attach_data ); 

echo $attach_id;
echo \'<pre>\';
print_r($filename);
echo \'</pre>\';
echo \'<pre>\';
print_r($attach_data);
echo \'</pre>\';
以下是输出:

96
Array
(
    [name] => one.png
    [type] => image/png
    [tmp_name] => /tmp/phphQ0e2v
    [error] => 0
    [size] => 144555
)
Array
(
)
如您所见,$attach\\u data为空:(

2 个回复
SO网友:fuxia

来自评论:

让WordPress生成一个文件路径,并将其用于接下来的步骤:

$upload    = wp_handle_upload($filename, array(\'test_form\' => false));
$attach_id = wp_insert_attachment( $attachment, $upload[\'file\'], $post_id );
wp_update_attachment_metadata( $attach_id,  $attach_data ); 

SO网友:hugo der hungrige

这就是最终为我解决问题的原因:

apply_filters(\'wp_handle_upload\', array(
    \'file\' => $file_path, 
    \'url\' => $file_url, 
    \'type\' => $file_type), 
\'upload\');
解释:我不太清楚为什么这会为我修复错误,但我假设这与使用wp\\u handle\\u upload hook的插件有关,或者过滤器会向附件添加元数据,否则wp\\u generate\\u attachment\\u metadata函数会丢失这些元数据。

全功能:

function add_to_media_lib($file_url, $file_path, $parent_post_id)
{
require_once(ABSPATH . \'wp-admin/includes/image.php\');
require_once(ABSPATH . \'wp-admin/includes/file.php\');

// Check the type of tile. We\'ll use this as the \'post_mime_type\'.
$file_type = wp_check_filetype(basename($file_url), null);

// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();

// Prepare an array of post data for the attachment.
$attachment = array(
    \'guid\' => $wp_upload_dir[\'url\'] . \'/\' . basename($file_url),
    \'post_mime_type\' => $file_type[\'type\'],
    \'post_title\' => preg_replace(\'/\\.[^.]+$/\', \'\', basename($file_url)),
    \'post_content\' => \'\',
    \'post_status\' => \'inherit\',
    \'post_parent\' => $parent_post_id
);

// Insert the attachment.
$attach_id = wp_insert_attachment($attachment, $file_url, $parent_post_id);

// apply filters (important in some environments)
apply_filters(\'wp_handle_upload\', array(\'file\' => $file_path, \'url\' => $file_url, \'type\' => $file_type), \'upload\');


// Generate the metadata for the attachment, and update the database record.
if ($attach_data = wp_generate_attachment_metadata($attach_id, $file_path)) {
    wp_update_attachment_metadata($attach_id, $attach_data);
} else {
    echo \'<div id="message" class="error"><h1>Failed to create PDF-thumbnail Meta-Data</h1><pre>\' . print_r($attach_data) . \'</pre></div>\';
}

return $attach_id;
}

结束