Importare prodotti in WooCommerce da un file Excel presente sul server può essere utile per automatizzare l'aggiornamento del catalogo. Questa guida mostra come realizzare una procedura personalizzata utilizzando PHP e la libreria PhpSpreadsheet
.
Requisiti
- WordPress con WooCommerce installato
- Accesso al server (FTP o SSH)
- Libreria
PhpSpreadsheet
installata tramite Composer
Installazione di PhpSpreadsheet
Accedi alla root del tuo progetto WordPress ed esegui il seguente comando:
composer require phpoffice/phpspreadsheet
Struttura del File Excel
Assicurati che il file Excel (es. products.xlsx
) contenga almeno queste colonne:
name
description
price
sku
category
4. Codice PHP per l'importazione
Inserisci questo script in un file PHP custom (es. import-prodotti.php
) nella root del tuo tema o plugin:
require __DIR__ . '/vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
function my_wc_import_products( $file_path ) {
$spreadsheet = IOFactory::load( $file_path );
$sheet = $spreadsheet->getActiveSheet();
$rows = $sheet->toArray();
foreach ( array_slice($ rows, 1 ) as $row ) {
[ $name, $description, $price, $sku, $category ] = $row;
$post_id = wp_insert_post([
'post_title' => $name,
'post_content' => $description,
'post_status' => 'publish',
'post_type' => 'product'
]);
if ( !is_wp_error( $post_id ) ) {
update_post_meta( $post_id, '_price', $price );
update_post_meta( $post_id, '_regular_price', $price );
update_post_meta( $post_id, '_sku', $sk u);
wp_set_object_terms( $post_id, $category, 'product_cat' );
}
}
}
// Percorso al file Excel presente sul server
$excel_file = __DIR__ . '/products.xlsx';
// Avvia l'importazione
my_wc_import_products( $excel_file );
Sicurezza
Non eseguire questo script da browser in produzione senza autenticazione. Proteggilo con un controllo di sicurezza o usalo solo in ambienti controllati.
Conclusione
Questa procedura consente di importare velocemente prodotti da un file Excel esistente sul server. Può essere personalizzata per gestire immagini, variabili, stock, e altre informazioni specifiche di WooCommerce.