【发布时间】:2019-03-20 21:54:26
【问题描述】:
我已经为我的插件创建了一个表单,它有两个上传字段;一个用于图像,一个用于 zip 文件。他们都使用相同的上传处理程序,我想将附件 ID 保存到数据库中。问题是它们使用相同的上传处理程序,因此带有附件 ID 的变量的值将始终是最后一个上传字段。最好的方法是如何做到这一点?保存在数组中(第一个索引是第一个字段,第二个索引是第二个字段)?两个上传处理程序可能有点矫枉过正。任何想法如何以一种好的方式解决这个问题?
这是处理上传的函数:
function releases_action(){
global $wpdb;
// Upload cover
$uploadfiles = $_FILES['uploadfiles'];
if (is_array($uploadfiles)) {
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
//clean filename and extract extension
$filename = $uploadfiles['name'][$key];
// get file info
// @fixme: wp checks the file extension....
$filetype = wp_check_filetype( basename( $filename ), null );
$filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
$filename = $filetitle . '.' . $filetype['ext'];
$upload_dir = wp_upload_dir();
/**
* Check if the filename already exist in the directory and rename the
* file if necessary
*/
$i = 0;
while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
$filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
$i++;
}
$filedest = $upload_dir['path'] . '/' . $filename;
/**
* Check write permissions
*/
if ( !is_writeable( $upload_dir['path'] ) ) {
$this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
return;
}
/**
* Save temporary file to uploads dir
*/
if ( !@move_uploaded_file($filetmp, $filedest) ){
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => $filetitle,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filedest );
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
}
正如我所说,由于两个上传字段使用相同的功能,$attach_ID 变量将是最新上传的值。
【问题讨论】:
-
您希望它们保存在数据库的哪个位置,还是只希望返回值?
-
现在我将 $attach_id 保存到数据库中的字段中。但是,正如我所写,$attach_id 将包含最新上传文件的值。
-
您正在使用 foreach 循环,因此您可以将 id 保存在循环中,并且它将具有该循环的正确值。查看答案,我附上了关于将代码放置在何处的注释。
-
所以我应该将它保存到函数内的数据库中?那不会给我一个表格的两个数据库连接吗?必须有更简单的方法吗?也许将它们保存到数组中?
-
您正在使用的函数已经使用了至少 2 个数据库连接。我不知道你想在哪里保存 id 以及你想如何拉它,但我在下面再放一点数组......
标签: php wordpress file-upload plugins