WordPress插件开发:如何将文件上传到默认"uploads"目录?



我正在尝试将文件上传到默认的"wp内容/上传";目录已经尝试了几乎所有可用的标签,但仍然不起作用。

我尝试过的代码很少:

  1. $filename = $_FILES["uploadfile"]["name"];$tempname=$_FILES["上传文件"]["tmp_name"];

    $folder='wp_upload_dir(('$文件名//此代码正在将文件上载到";wp-admin";目录

    if(move_uploaded_file($tempname,$folder(({$response}

  2. $uploaddir = 'uploads/';$uploadfile=$uploaddir$文件名;`

    if(move_uploaded_file($tempname, $uploadfile))

`

我已经编码将图像保存在我的一个网站的上传文件夹中。请检查此代码是否有助于

//taking image in $name_icon
$name_icon = $_POST['myfile'];

// WordPress environment
require( dirname(__FILE__) . '/../../../wp-load.php' );

$wordpress_upload_dir = wp_upload_dir();

$i = 1; // number of tries when the file with the same name is already exists

$profilepicture = $_FILES['myfile'];
$new_file_path = $wordpress_upload_dir['path'] . '/' . $profilepicture['name'];
$new_file_mime = mime_content_type( $profilepicture['tmp_name'] );

if( empty( $profilepicture ) )
die();

if( $profilepicture['error'] )
die( $profilepicture['error'] );

if( $profilepicture['size'] > wp_max_upload_size() )
die( 'It is too large than expected.' );

if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
die( 'WordPress doesn't allow this type of uploads.' );

while( file_exists( $new_file_path ) ) {
$i++;
$new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $profilepicture['name'];
}

// looks like everything is OK
if( move_uploaded_file( $profilepicture['tmp_name'], $new_file_path ) ) {

$upload_id = wp_insert_attachment( array(
'guid'           => $new_file_path, 
'post_mime_type' => $new_file_mime,
'post_title'     => preg_replace( '/.[^.]+$/', '', $profilepicture['name'] ),
'post_content'   => '',
'post_status'    => 'inherit'
), $new_file_path );

// wp_generate_attachment_metadata() won't work if you do not include this file
require_once( ABSPATH . 'wp-admin/includes/image.php' );

// Generate and save the attachment metas into the database
wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );

测试&工作

最新更新