Come importare immagini da OneDrive nella Media Library di WordPress

Come importare immagini da OneDrive nella Media Library di WordPress

Importare automaticamente immagini da una directory di OneDrive nella Media Library di WordPress è utile per aggiornare contenuti dinamici da una fonte esterna. In questa guida, vedremo come autenticarsi con le API di Microsoft Graph, scaricare le immagini da una cartella di OneDrive e importarle in WordPress.

Requisiti

  • Account Microsoft con accesso a OneDrive
  • App registrata su Azure Portal
  • Token di accesso Microsoft Graph
  • Ambiente WordPress con accesso a codice personalizzato (es. plugin o tema child)

Autenticazione con Microsoft Graph

Per usare le API di OneDrive è necessario ottenere un token di accesso OAuth2. Dopo aver registrato un'app su Azure Portal, otterrai:

  • Client ID
  • Client Secret
  • Refresh Token (da ottenere inizialmente con login interattivo)

Puoi ottenere un nuovo access_token da un refresh_token con una richiesta POST:

POST https://login.microsoftonline.com/common/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded

client_id=YOUR_CLIENT_ID
&scope=https://graph.microsoft.com/.default
&refresh_token=YOUR_REFRESH_TOKEN
&grant_type=refresh_token
&client_secret=YOUR_CLIENT_SECRET

Recuperare immagini da OneDrive

La funzione seguente restituisce l'elenco delle immagini in una specifica cartella pubblica di OneDrive, usando Microsoft Graph API:

function get_onedrive_images($access_token, $folder_path = '/Immagini') {
    $endpoint = 'https://graph.microsoft.com/v1.0/me/drive/root:' . rawurlencode($folder_path) . ':/children';

    $response = wp_remote_get($endpoint, array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $access_token
        )
    ));

    if (is_wp_error($response)) {
        return array();
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);

    if (!isset($body['value'])) {
        return array();
    }

    $images = array_filter($body['value'], function($item) {
        return isset($item['@microsoft.graph.downloadUrl']) &&
               preg_match('/\.(jpg|jpeg|png|gif)$/i', $item['name']);
    });

    return $images;
}

Scaricare le immagini sul server

Scarichiamo ciascuna immagine nel filesystem locale di WordPress:

function download_image_from_onedrive($image_url, $filename) {
    $response = wp_remote_get($image_url);

    if (is_wp_error($response)) {
        return false;
    }

    $upload_dir = wp_upload_dir();
    $file_path = $upload_dir['path'] . '/' . $filename;

    file_put_contents($file_path, wp_remote_retrieve_body($response));

    return $file_path;
}

Importare l'immagine nella Media Library

Questa funzione registra l'immagine come allegato di WordPress:

function import_to_media_library($file_path, $filename) {
    $filetype = wp_check_filetype($filename, null);
    $upload_dir = wp_upload_dir();

    $attachment = array(
        'guid'           => $upload_dir['url'] . '/' . basename($file_path),
        'post_mime_type' => $filetype['type'],
        'post_title'     => sanitize_file_name($filename),
        'post_content'   => '',
        'post_status'    => 'inherit'
    );

    $attach_id = wp_insert_attachment($attachment, $file_path);

    require_once(ABSPATH . 'wp-admin/includes/image.php');

    $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
    wp_update_attachment_metadata($attach_id, $attach_data);

    return $attach_id;
}

Eseguire il processo completo

Questa funzione principale gestisce l’intero processo di download e importazione:

function import_onedrive_images($access_token, $folder_path = '/Immagini') {
    $images = get_onedrive_images($access_token, $folder_path);

    foreach ($images as $image) {
        $filename = sanitize_file_name($image['name']);
        $download_url = $image['@microsoft.graph.downloadUrl'];

        $file_path = download_image_from_onedrive($download_url, $filename);
        if ($file_path) {
            import_to_media_library($file_path, $filename);
        }
    }
}

Conclusione

Grazie a questa procedura è possibile automatizzare l’importazione di immagini da OneDrive a WordPress, integrando una sorgente esterna di contenuti con la libreria multimediale del sito. È possibile programmare l’esecuzione del processo con un sistema di cron interno o esterno per aggiornamenti periodici.