使用wp_handle_upload
在自定义函数中
if ( $_FILES ) {
upload_user_file($_FILES[\'test_upload\']);
}
if ( ! function_exists( \'upload_user_file\' ) ) :
function upload_user_file( $file = array(), $title = false ) {
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_content\' => \'\',
\'post_type\' => \'attachment\',
\'post_status\' => \'inherit\',
\'guid\' => $file_return[\'url\']
);
if($title){
$attachment[\'post_title\'] = $title;
}
$attachment_id = wp_insert_attachment( $attachment, $filename );
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;
}
endif;