我正在Wordpress中进行一个简单的前端图像上传。有了这段代码,我可以上传到wordpress媒体部分,但我只上传文件的名称和url,没有图像。
有人知道我需要做什么才能上传图像吗?
我的表格:
<form id="dash_action" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input name="submit" type="submit" class="button" value="<?php _e( \'Save settings\' ); ?>" />
</form><!--End dash_action-->
我的PHP表单处理:
if( isset( $_POST[\'submit\'] ) ) {
$filename = $_FILES[\'file\'][\'name\'];
$wp_filetype = wp_check_filetype( basename($filename), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
\'guid\' => $wp_upload_dir[\'subdir\'] . \'/\' . basename( $filename ),
\'post_mime_type\' => $wp_filetype[\'type\'],
\'post_title\' => preg_replace( \'/\\.[^.]+$/\', \'\', basename( $filename ) ),
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
$attach_id = wp_insert_attachment( $attachment, $filename, 37 );
require_once( ABSPATH . \'wp-admin/includes/image.php\' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
最合适的回答,由SO网友:James Austen 整理而成
这个WordPress codex 声明“文件必须位于uploads目录”。我添加了一行代码,将上载的文件移动到上载目录中,并更改了guid路径。
if( isset( $_POST[\'submit\'] ) ) {
$filename = $_FILES[\'file\'][\'name\'];
$wp_filetype = wp_check_filetype( basename($filename), null );
$wp_upload_dir = wp_upload_dir();
// Move the uploaded file into the WordPress uploads directory
move_uploaded_file( $_FILES[\'file\'][\'tmp_name\'], $wp_upload_dir[\'path\'] . \'/\' . $filename );
$attachment = array(
\'guid\' => $wp_upload_dir[\'url\'] . \'/\' . basename( $filename ),
\'post_mime_type\' => $wp_filetype[\'type\'],
\'post_title\' => preg_replace( \'/\\.[^.]+$/\', \'\', basename( $filename ) ),
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
$filename = $wp_upload_dir[\'path\'] . \'/\' . $filename;
$attach_id = wp_insert_attachment( $attachment, $filename, 37 );
require_once( ABSPATH . \'wp-admin/includes/image.php\' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
SO网友:Tom J Nowell
media_handle_sideload
is your friend!
用法:
media_handle_sideload( $file_array, $post_id, $desc, $post_data );
因此,您的代码的大小大大减少到:
if( isset( $_POST[\'submit\'] ) ) {
$attach_id = media_handle_sideload( $_FILES[\'file\'], 0, \'description\' );
}
您还可以传入带有标题等的帖子数据数组
它会自动将您的文件移动到正确的位置,创建一个附件并生成元数据,将其附加到相关帖子,并作为回报给您一个附件ID。
确保使用is_wp_error()
检查故障。