A volte in WordPress possiamo avere necessità di inserire file esistenti nella Media Library. Vediamo in dettaglio una soluzione.
Possiamo definire la seguente funzione:
function my_insert_file_into_media_library( $filepath = '' ) {
if( !file_exists( $filepath ) || !is_readable( $filepath ) ) {
return 0;
}
$filename = basename( $filepath );
$wp_filetype = wp_check_filetype( $filename, null );
$attachment = [
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', $filename ),
'post_content' => '',
'post_status' => 'inherit',
];
$attachment_id = wp_insert_attachment( $attachment, $filepath );
if( !$attachment_id ) {
return 0;
}
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filepath );
if( !wp_update_attachment_metadata( $attachment_id, $attachment_data ) ) {
return 0;
}
return $attachment_id;
}
La funzione verifica l'esistenza del file e l'accesso allo stesso e quindi procede a generare l'allegato e i suoi metadati utilizzando le API e le funzionalità core di WordPress. Restituisce l'ID dell'allegato o 0 in caso di errore.