WordPress update theme after install in PHP loop (Theme_Upgrader)

I’m working on a plugin that will automatically download a theme from a list, then update, and activate it.

Considering there are a number of potential errors (i.e. improper PHP version, etc), I’m trying to make it re-try after encountering an error.

The problem is that if the first theme fails (in this case, because of a PHP error – requires 7.2, I am testing with 7.0), WordPress will not perform the update on the second theme (retrogeek.0.4.zip).

However, if I make retrogeek.0.4.zip the first theme in the list, WordPress will automatically update the theme. This appears to be some sort of caching issue, but I’ve been trying for 3+ hours now and cannot get it to work.

I’ve tried a ton of variations of wp_clean_themes_cache(false) and anything else I can find. There really isn’t much documentation on this sort of thing.

I’ve also tried:

  • Nulling $test_theme_installer at the end of the loop
  • Making $test_theme_install->upgrade a variable and nulling it
  • Using “bulk_upgrade” outside of the loop

Here is the code I have now:

require_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php');
require_once(ABSPATH . 'wp-admin/includes/class-theme-upgrader.php');

$grab_theme_url = array(
        'https://downloads.wordpress.org/theme/sirat.0.8.8.zip',
        'https://downloads.wordpress.org/theme/retrogeek.0.4.zip',
);

for($i=0; $i < 3; $i++) {

 $grab_theme_url = $grab_theme_url[$i];
 $theme_folder_path = ABSPATH . "wp-content/themes/";
 $theme_zip_file = basename(parse_url($grab_theme_url, PHP_URL_PATH));

 copy($grab_theme_url, $theme_folder_path . $theme_zip_file);

 $theme_file_unzipped = preg_replace('/.(.*)/','',$theme_zip_file);

 // ----------------------------------------------------------------------------------------
 //  Install and update the theme
 // ----------------------------------------------------------------------------------------
 $args = array('clear_update_cache' => false);

 $test_theme_install = new Theme_Upgrader();
 $test_theme_installer = $test_theme_install->install($theme_folder_path . $theme_zip_file, $args);

 if($test_theme_installer !== null) {
     $test_theme_install->upgrade($theme_file_unzipped, $args);
     break;
 }
     echo "Theme incompatible... trying again.";
     unlink($theme_folder_path . $theme_zip_file);

}