在前端,我创建了一个表单,该表单使用upload_user_file()
从正面主题上传文件,并且每个图像都很好地存储在WordPress媒体库中(看起来是这样)。
因此,当我上传名为test.jpg
的文件时,将创建其相对缩略图并在媒体库中可见。测试-150x150.jpg测试-300x225.jpg测试-1024x768.jpg
我遇到的问题是当我从媒体库中删除此图像时。仅删除创建的缩略图,上传文件夹中test.jpg
保持不变。如果我直接从媒体库上传此文件,然后将其删除,则删除所有文件,包括test.jpg
.
下面是将值存储在数据库中并将文件上传到媒体库的代码。有没有另一个WordPress功能可以使用?我想upload_user_file()
没有将图像数据正确存储在数据库中?
global $wpdb;
global $post;
//$table = 'wp_verk1_project'; //$post_slug=$post->post_name;
$table = $wpdb->prefix . "project_name_" . $post_slug=$post->post_name;
$data = array(
'contributorname' => $_POST['yourname'],
'email' => $_POST['email'],
'telephone' => $_POST['telephone'],
'description' => $_POST['description'],
'date' => date('Y-m-d'),
'time' => date('H:i:s'),
'upload' => upload_user_file($_FILES['file']),
'upload2' => upload_user_file($_FILES['file2']),
'upload3' => upload_user_file($_FILES['file3']),
'upload4' => upload_user_file($_FILES['file4']),
'upload5' => upload_user_file($_FILES['file5']),
'rate' => '0'
);
$format = array(
'%s',
'%s'
);
$success = $wpdb->insert($table, $data, $format);
if ($success) {
header("Location: " . get_bloginfo('url') . "/thank-you/");
exit();
}
edit_user_file():
function upload_user_file( $file = array() ) {
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
$file_return = wp_handle_upload( $file, array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/'.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
require_once (ABSPATH . 'wp-admin/includes/image.php' );
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
亲切问候Johan
我设法解决了我自己的问题。
我深入研究了WordPress核心文件。
我替换了以下行:
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
有了这个:
$attachment_id = wp_insert_attachment( $attachment, $filename );
在wp_postmeta中,上传meta_value设置为完整的 url (http://sitenamen.com/wp-content/upload/2014/12/file.jpg),而它应该像这样存储:2014/12/file.jpg
现在所有文件都将被删除。