¿Deseas subir archivos enviados por el usuario a la biblioteca de medios? Este fragmento se encargará de subir archivos a tu biblioteca de medios.
Instrucciones
- Agrega este código al archivo functions.php de tu tema o a un plugin específico del sitio.
- All uploaded files are stored in the $_FILES array, so you will need to loop through the
$_FILESarray and pass each file array to theupload_user_file()function. You can use this code in your form handler:
if( ! empty( $_FILES ) ) { foreach( $_FILES as $file ) { if( is_array( $file ) ) { $attachment_id = upload_user_file( $file ); } } } - Recuerda que si quieres que tu formulario pueda manejar subidas de archivos, entonces necesitas agregar el atributo
enctype="multipart/form-data"a la etiqueta<form>.
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;
}
Nota: Si es la primera vez que agregas fragmentos de código en WordPress, consulta nuestra guía sobre cómo copiar / pegar fragmentos de código correctamente en WordPress, para que no rompas accidentalmente tu sitio.
Si te gustó este fragmento de código, considera consultar Cómo configurar el seguimiento de descargas en WordPress con Google Analytics
Genial, ¿hay algún código que permita previsualizar el archivo?
Estoy seguro de que se podría hacer cualquier cosa, pero no tiene una vista previa del archivo.