Vuoi caricare file inviati dagli utenti nella libreria multimediale? Questo snippet gestirà il caricamento dei file nella tua libreria multimediale.
Istruzioni
- Aggiungi questo codice al file functions.php del tuo tema o a un plugin specifico per il sito.
- 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 ); } } } - Ricorda che se vuoi che il tuo form sia in grado di gestire i caricamenti di file, devi aggiungere l'attributo
enctype="multipart/form-data"al tag<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: Se questa è la prima volta che aggiungi snippet di codice in WordPress, consulta la nostra guida su come copiare / incollare correttamente snippet di codice in WordPress, in modo da non rompere accidentalmente il tuo sito.
Se ti è piaciuto questo snippet di codice, prendi in considerazione la lettura di Come impostare il monitoraggio dei download in WordPress con Google Analytics
Fantastico, c'è un codice per visualizzare in anteprima il file?
Sono sicuro che si possa fare qualsiasi cosa, ma non c'è un'anteprima del file.