您可以使用WordPress的内置上载处理程序,wp_handle_upload(). 您可以使用upload_dir
筛选以设置自定义目录。
以下是我的一个插件中的一些代码片段,您可以使用/修改:
public function saveCustomFields()
{
global $post;
if($post->post_type == self::POST_TYPE && current_user_can( \'edit_post\', $post->ID ) )
{
if ( defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE )
return;
$fileReference = \'installPDF\'; // This has to be in a variable because it gets passed by reference to wp_handle_upload()
// save normal custom fields w/ update_post_meta() here
if( empty($_FILES[$fileReference] ) )
{
// your custom logic if needed
}
else
{
$overrides = array(
\'test_form\' => false,
\'unique_filename_callback\' => self::PREFIX . \'setFilename\' // this lets you rename the file
);
$result = wp_handle_upload( $_FILES[$fileReference], $overrides );
if( is_array($result) && array_key_exists(\'error\', $result) && !empty( $result[\'error\'] ) )
{
// failure logic
}
else
{
// success logic
}
}
}
}
add_action( \'post_updated\', array( $this, \'saveCustomFields\') );
public function addFormEnctype()
{
// this is needed to enable file uplodas on your form
echo \' enctype="multipart/form-data"\';
}
add_action( \'post_edit_form_tag\', array( $this, \'addFormEnctype\') );
public function setUploadDirectory($uploads)
{
global $post;
if( $post->post_type == self::POST_TYPE )
{
$uploads[\'path\'] = $this->uploadDir . $this->uploadYear .\'/\';
$uploads[\'url\'] = $this->uploadURL . $this->uploadYear .\'/\';
$uploads[\'subdir\'] = \'/\'. $this->uploadYear;
$uploads[\'basedir\'] = $this->uploadDir;
$uploads[\'baseurl\'] = $this->uploadURL;
}
return $uploads;
}
add_filter( \'upload_dir\', array( $this, \'setUploadDirectory\') );