Here's a sample code snippet to import product data into WooCommerce using the built-in WooCommerce CSV importer:
php
<?php
// Make sure WooCommerce is active
if (!function_exists('WC')) {
return;
}
// File path to your CSV
$file = WP_PLUGIN_DIR . '/woocommerce/sample-data/sample_products.csv';
// Get the WC_Product_CSV_Importer class
require_once WC_ABSPATH . 'includes/import/class-wc-product-csv-importer.php';
// Set up import parameters
$params = array(
'parse' => true,
'prevent_timeouts' => false,
'mapping' => array(
'from' => array('name', 'description', 'short_description', 'price', 'regular_price', 'sale_price', 'stock_quantity'),
'to' => array('name', 'description', 'short_description', 'price', 'regular_price', 'sale_price', 'stock_quantity')
),
'update_existing' => false,
'delimiter' => ',',
);
// Create the importer object
$importer = new WC_Product_CSV_Importer($file, $params);
// Run the import
$results = $importer->import();
// Check for errors
if (is_wp_error($results)) {
echo "Import failed: " . $results->get_error_message();
} else {
echo "Import successful. " . count($results) . " products imported.";
}
This code does the following:
1. It checks if WooCommerce is active[1].
2. It specifies the path to the CSV file containing product data. In this example, it uses the sample data provided by WooCommerce[1].
3. It loads the WC_Product_CSV_Importer class[2].
4. It sets up import parameters, including mapping CSV columns to WooCommerce product fields[2][4].
5. It creates an importer object and runs the import[2][4].
6. Finally, it checks for errors and reports the results[4].
To use this code:
1. Make sure you have a valid CSV file with product data.
2. Adjust the `$file` path to point to your CSV file.
3. Modify the `mapping` array if your CSV has different column names.
4. Run this code in a PHP file or as part of a WordPress plugin.
Remember to back up your database before running any import scripts. Also, for large datasets, you may need to adjust PHP execution time and memory limits[4].
This is a basic example. For more complex imports or specific needs, you might need to extend this code or use WooCommerce hooks to customize the import process further[2][4].
Citations:[1] https://woocommerce.com/document/importing-woocommerce-sample-data/
[2] https://woocommerce.com/document/product-csv-importer-exporter/
[3] https://diviengine.com/downloading-and-importing-woocommerce-sample-data/
[4] https://www.wpallimport.com/documentation/import-woocommerce-data-from-csv-excel-xml/
[5] https://woocommerce.com/document/product-csv-import-suite/product-csv-import-suite-importing-products/