Hi Nobby,
For importing subscribers into a WooCommerce site specifically, you can leverage WordPress and WooCommerce functionalities with a bit of custom PHP code. However, since subscribers are essentially WordPress users with a specific role, you’ll be working with WordPress user functions primarily.
Here’s a simple approach using a custom PHP script. This script reads your CSV file and imports each subscriber as a WordPress user with the role of ‘customer’ (commonly used by WooCommerce for customers/subscribers). Before proceeding, ensure your CSV is formatted with the necessary columns (e.g., email, first name, last name). Adjust the column names in the script as needed to match your CSV.
Make sure your CSV file has headers that at least include email
, first_name
, and last_name
. Adjust your CSV or the script according to the data you have.
You can then add the following code to your theme’s functions.php
file and run your import. This code will:
- Add a new page to the Tools menu in the WordPress admin for importing subscribers from a CSV file.
- Provide an upload form on this new page.
- Handle the file upload securely, with basic validation and sanitization.
- Process the CSV file to create or update users with the role of ‘customer’.
function csv_importer_admin_menu() {
add_management_page('Import CSV', 'Import CSV', 'manage_options', 'import-csv', 'csv_importer_upload_form');
}
add_action('admin_menu', 'csv_importer_admin_menu');
function csv_importer_upload_form() {
?>
<div class="wrap">
<h2>Import Subscribers from CSV</h2>
<form method="post" enctype="multipart/form-data">
<input type="file" name="csv_import" id="csv_import" accept=".csv">
<?php submit_button('Import CSV'); ?>
</form>
</div>
<?php
}
function csv_importer_handle_upload() {
if (isset($_FILES['csv_import']) && current_user_can('manage_options')) {
if ($_FILES['csv_import']['error'] === UPLOAD_ERR_OK && $_FILES['csv_import']['type'] === 'text/csv') {
$csv_path = $_FILES['csv_import']['tmp_name'];
$handle = fopen($csv_path, 'r');
if ($handle !== FALSE) {
fgetcsv($handle); // Assuming the first row contains headers
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
$email = sanitize_email($data[0]);
$first_name = sanitize_text_field($data[1]);
$last_name = sanitize_text_field($data[2]);
if (!email_exists($email)) {
$user_id = wp_create_user($email, wp_generate_password(), $email);
wp_update_user([
'ID' => $user_id,
'first_name' => $first_name,
'last_name' => $last_name,
'role' => 'customer'
]);
}
}
fclose($handle);
add_action('admin_notices', function() { echo '<div class="updated"><p>Subscribers imported successfully.</p></div>'; });
}
} else {
add_action('admin_notices', function() { echo '<div class="error"><p>There was an error with the upload. Please ensure you are uploading a CSV file.</p></div>'; });
}
}
}
add_action('admin_init', 'csv_importer_handle_upload');