Last active
December 12, 2024 19:52
-
-
Save MoatazAbdAlmageed/8ad9c283ca38731fd6984f001c65f9b2 to your computer and use it in GitHub Desktop.
Bulk Import Students into WordPress LearnPress
We can make this file beautiful and searchable if this error is corrected: It looks like row 2 should actually have 3 columns, instead of 4 in line 1.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Email addresses,Full names,courses | |
"moataz.mohammady@gmail,com",moataz mohammady,4305,4306 | |
"moohamed.mohammady@gmail,com",moohamed mohammady,4305 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: LearnPress Student Bulk Import | |
* Description: Imports students from CSV file into LearnPress and enrolls them in multiple courses | |
* Version: 1.6 | |
*/ | |
// Prevent direct access | |
if (!defined('ABSPATH')) { | |
exit; | |
} | |
// Add menu item under LearnPress | |
add_action('admin_menu', function() { | |
add_submenu_page( | |
'learn_press', | |
'Bulk Import Students', | |
'Bulk Import Students', | |
'manage_options', | |
'lp-bulk-import', | |
'lp_bulk_import_page' | |
); | |
}); | |
function enroll_user_to_course($user_id, $course_id) { | |
// Check if course exists | |
$course = get_post($course_id); | |
if (!$course || $course->post_type !== 'lp_course') { | |
return false; | |
} | |
// Check if already enrolled | |
$enrolled = get_user_meta($user_id, '_lp_course_' . $course_id, true); | |
if ($enrolled) { | |
return true; | |
} | |
global $wpdb; | |
// Insert user item (enrollment record) | |
$user_item_data = array( | |
'user_id' => $user_id, | |
'item_id' => $course_id, | |
'start_time' => current_time('mysql'), | |
'item_type' => 'lp_course', | |
'status' => 'enrolled', | |
'ref_id' => $course_id, | |
'ref_type' => 'lp_course' | |
); | |
$wpdb->insert( | |
$wpdb->prefix . 'learnpress_user_items', | |
$user_item_data, | |
array('%d', '%d', '%s', '%s', '%s', '%d', '%s') | |
); | |
if ($wpdb->insert_id) { | |
// Add user meta to mark enrollment | |
update_user_meta($user_id, '_lp_course_' . $course_id, 'enrolled'); | |
return true; | |
} | |
return false; | |
} | |
function lp_bulk_import_page() { | |
if (isset($_POST['import_students']) && isset($_FILES['student_file'])) { | |
handle_file_import(); | |
} | |
?> | |
<div class="wrap"> | |
<h2>Import Students</h2> | |
<p>Upload a CSV file with three columns: email, full name, and courses. First row should be headers.</p> | |
<p><strong>Note:</strong></p> | |
<ul> | |
<li>Password will be set as: email+123456#</li> | |
<li>Courses column should contain course IDs separated by commas (e.g., 4305,4306)</li> | |
</ul> | |
<form method="post" enctype="multipart/form-data"> | |
<input type="file" name="student_file" accept=".csv" required> | |
<input type="submit" name="import_students" class="button button-primary" value="Import"> | |
</form> | |
</div> | |
<?php | |
} | |
function handle_file_import() { | |
try { | |
$file = $_FILES['student_file']['tmp_name']; | |
if (!is_uploaded_file($file)) { | |
throw new Exception('No file uploaded'); | |
} | |
$handle = fopen($file, 'r'); | |
if (!$handle) { | |
throw new Exception('Could not open file'); | |
} | |
// Skip header row | |
fgetcsv($handle); | |
$created = 0; | |
$updated = 0; | |
$enrolled = 0; | |
$failures = 0; | |
$error_messages = array(); | |
$processed_users = array(); | |
while (($row = fgetcsv($handle)) !== false) { | |
if (count($row) < 3) { | |
$failures++; | |
$error_messages[] = "Skipped row: insufficient data"; | |
continue; | |
} | |
$email = sanitize_email($row[0]); | |
$full_name = sanitize_text_field($row[1]); | |
$course_ids = array_map('trim', explode(',', $row[2])); | |
if (!is_email($email)) { | |
$failures++; | |
$error_messages[] = "Invalid email: $email"; | |
continue; | |
} | |
$password = $email . '123456#'; | |
$existing_user_id = email_exists($email); | |
$enrollment_results = array(); | |
if ($existing_user_id) { | |
// Update existing user | |
wp_set_password($password, $existing_user_id); | |
wp_update_user([ | |
'ID' => $existing_user_id, | |
'display_name' => $full_name, | |
'first_name' => explode(' ', $full_name)[0], | |
'last_name' => array_slice(explode(' ', $full_name), 1) ? implode(' ', array_slice(explode(' ', $full_name), 1)) : '', | |
]); | |
$user = new WP_User($existing_user_id); | |
$user->add_role('lp_student'); | |
$user_id = $existing_user_id; | |
$updated++; | |
$status = 'Updated'; | |
} else { | |
// Create new user | |
$username = explode('@', $email)[0]; | |
$base_username = $username; | |
$counter = 1; | |
while (username_exists($username)) { | |
$username = $base_username . $counter; | |
$counter++; | |
} | |
$user_id = wp_create_user($username, $password, $email); | |
if (!is_wp_error($user_id)) { | |
wp_update_user([ | |
'ID' => $user_id, | |
'display_name' => $full_name, | |
'first_name' => explode(' ', $full_name)[0], | |
'last_name' => array_slice(explode(' ', $full_name), 1) ? implode(' ', array_slice(explode(' ', $full_name), 1)) : '', | |
]); | |
$user = new WP_User($user_id); | |
$user->set_role('lp_student'); | |
$created++; | |
$status = 'Created'; | |
} else { | |
$failures++; | |
$error_messages[] = "Failed to create user: " . $user_id->get_error_message(); | |
continue; | |
} | |
} | |
// Enroll in courses | |
foreach ($course_ids as $course_id) { | |
if (!empty($course_id)) { | |
$enrollment_status = enroll_user_to_course($user_id, $course_id); | |
if ($enrollment_status) { | |
$enrolled++; | |
$enrollment_results[] = "Course $course_id: Success"; | |
} else { | |
$enrollment_results[] = "Course $course_id: Failed"; | |
} | |
} | |
} | |
$processed_users[] = array( | |
'email' => $email, | |
'password' => $password, | |
'full_name' => $full_name, | |
'status' => $status, | |
'enrollment' => implode(', ', $enrollment_results) | |
); | |
} | |
fclose($handle); | |
echo '<div class="notice notice-success"><p>'; | |
echo "Import completed:<br>"; | |
echo "- $created new students created<br>"; | |
echo "- $updated existing students updated<br>"; | |
echo "- $enrolled successful course enrollments<br>"; | |
echo "- $failures failed<br><br>"; | |
if (!empty($processed_users)) { | |
echo "<strong>Processed accounts:</strong><br>"; | |
echo "<table class='wp-list-table widefat fixed striped'>"; | |
echo "<thead><tr><th>Email</th><th>Password</th><th>Full Name</th><th>Status</th><th>Course Enrollments</th></tr></thead><tbody>"; | |
foreach ($processed_users as $user) { | |
echo "<tr>"; | |
echo "<td>" . esc_html($user['email']) . "</td>"; | |
echo "<td>" . esc_html($user['password']) . "</td>"; | |
echo "<td>" . esc_html($user['full_name']) . "</td>"; | |
echo "<td>" . esc_html($user['status']) . "</td>"; | |
echo "<td>" . esc_html($user['enrollment']) . "</td>"; | |
echo "</tr>"; | |
} | |
echo "</tbody></table>"; | |
} | |
if (!empty($error_messages)) { | |
echo "<br><strong>Errors:</strong><br>" . implode("<br>", array_slice($error_messages, 0, 10)); | |
if (count($error_messages) > 10) { | |
echo "<br>... and " . (count($error_messages) - 10) . " more errors"; | |
} | |
} | |
echo '</p></div>'; | |
} catch (Exception $e) { | |
echo '<div class="notice notice-error"><p>'; | |
echo 'Error: ' . $e->getMessage(); | |
echo '</p></div>'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment