Site icon Hip-Hop Website Design and Development

Generating 10 000 WordPress posts using PHP and avoiding Server Timeout error

I hope someone would be able to help me. I’m currently trying to develop a plugin which is able to generate 10 000 WP posts, each with different number (basically, 10 000 posts which title is a different number).

I was hoping to do that with a single PHP operation like this:

    $numbers = array(0, 0, 0, 0, 0);
    $full_number;
    for ($i = 0; $i <= 9; $i++) {
        for ($j = 0; $j <= 9; $j++) {
            for ($q = 0; $q <= 9; $q++) {
                for ($k = 0; $k <= 9; $k++) {
                    for ($t = 0; $t <= 9; $t++) {
                        $post_id_number++; 
                        $numbers[0] = $i;
                        $numbers[1] = $j;
                        $numbers[2] = $q;
                        $numbers[3] = $k;
                        $numbers[4] = $t;
                        $full_number = $numbers[0] . $numbers[1] . $numbers[2] . $numbers[3] . $numbers[4];
                        $full_number_string = strval($full_number);
                        wp_insert_post( array(
                            
                            'post_title' => $full_number_string,
                            'post_type' => 'numbers'
                        ) );
                    }
                }                   
            }
        }
    }

However, I always run into Server Timeout error. I tried using set_time_limit() function but then the code just keeps working infinitely after I pressed the form button. This is the form code:

      <div class="wrap">
      <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
      <form action="" method="post">
      </form>
      <?php
        if ( isset($_POST['submit'] ) ) {
            custom_phone_numbers_generate_numbers();
            echo "submited";
        }           
      ?>
    </div>

Could anyone tell me a better approach? Is it possible to use AJAX in this situation? If yes, then how?