可以使用media\\u handle\\u upload()函数执行此操作。这是一个工作示例,您可以将其用作需求指南:
首先创建HTML表单
<form method="post" id="uploadCartaAnno" enctype=\'multipart/form-data\'>
<input class="text-input" name="carta_ano" type="file" id="carta_ano" multiple="false"/>
<?php wp_nonce_field( \'my_image_upload\', \'my_image_upload_nonce\' ); ?>
<input name="updatecarta_ano" type="submit" id="updatecarta_ano" class="hp-btn-file -icon-upload" value="Subir formato" />
<input name="action" type="hidden" id="action" value="update-user" />
</form>
然后是您的PHP代码
if (
isset( $_POST[\'my_image_upload_nonce\'] )
&& wp_verify_nonce( $_POST[\'my_image_upload_nonce\'], \'my_image_upload\' )
) {
// The nonce is valid and it is safe to continue.
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . \'wp-admin/includes/image.php\' );
require_once( ABSPATH . \'wp-admin/includes/file.php\' );
require_once( ABSPATH . \'wp-admin/includes/media.php\' );
// Let WordPress handle the upload.
$attachment_id = media_handle_upload( \'carta_ano\', $comId );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
} else {
// The image was uploaded successfully!
}
} else {
// Show some error message if nonce fails.
}