下面的代码用于通过表单上载文件。。。我想更改上载到主题根目录中名为abc的文件夹的默认上载路径。
我希望有人能帮我,下面是我的代码
<?php
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;
}
?>
表格
<?php
if(isset($_POST[\'upload\']))
{
if( ! empty( $_FILES ) )
{
$file=$_FILES[\'file\'];
$attachment_id = upload_user_file( $file );
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="upload">
</form>
最合适的回答,由SO网友:TheDeadMedic 整理而成
不要将用户上传的内容存储在主题文件夹中!我建议您将它们存储在默认上载文件夹的子目录中。
您可以使用upload_dir
筛选以临时更改路径:
function wpse_183245_upload_dir( $dirs ) {
$dirs[\'subdir\'] = \'/abc\';
$dirs[\'path\'] = $dirs[\'basedir\'] . \'/abc\';
$dirs[\'url\'] = $dirs[\'baseurl\'] . \'/abc\';
return $dirs;
}
然后在使用中:
add_filter( \'upload_dir\', \'wpse_183245_upload_dir\' );
// Your upload code
remove_filter( \'upload_dir\', \'wpse_183245_upload_dir\' );