For loop does not do all iterations
-
I am trying to create about 500 users in a for loop using wp_insert_user(), but the for loop doesn’t loop fully. It sometimes stops after 20 iterations, sometimes after 50 items, but never iterates fully.
This issue seems to be a general issue with for loop & for each loop in wordpress and not about creating users alone as I faced this issue when looping through users fetched via WP_User_Query.
I have increased the maximum execution time to 60 minutes via set_time_limit(60*60), but still no luck.
Please let me know how to get for & for each loops to loop through all iterations.
I have enabled debug logs and I did not see any errors indicating why it stopped iterating abruptly through the for loop.
// Child theme functions.php function some_function() { ... wp_schedule_single_event( time() + 10, 'my_hook_create_test_users', $method_args); ... } add_action( 'my_hook_create_test_users', 'my_create_test_users', 10, 1 ); function my_create_test_users($method_args) { $default_max_time_limit = ini_get( 'max_execution_time' ); $time_limit_changed = set_time_limit(60*60); try { for($index = 0; $index < 500; $index++) { $userdata = array( 'ID' => 0, 'user_pass' => 'kadjkashdjkad', 'user_login' => 'my_test_user_'.$index, 'user_email' => 'my_test_user_'.$index.'@email.com', 'first_name' => 'my_test_user_'.$index.'_FN', 'last_name' => 'my_test_user_'.$index.'_LN', 'role' => 'subscriber', 'meta_input' => array( 'my_is_test_user' => 'true', 'my_user_type' => 'paid', 'my_membership_purchase_date' => time(), ) ); $userid = wp_insert_user( $userdata ); if ( !is_wp_error( $userid ) ) { // check if insert was successful error_log("Test user ".$user->user_email." created."); } else { /* Error Handling */ error_log("Exception while creating test user with email: ".$userdata['email']); } } } catch(Exception $e) { error_log("Exception while processing my_create_test_users: ".$e->getMessage()); } finally { set_time_limit($default_max_time_limit); } }
- The topic ‘For loop does not do all iterations’ is closed to new replies.