1

I'm developing a WordPress plugin.

I want to download a file from a server, then unzip and put it inside the main directory of WordPress after the plugin is activated. The process of download and unzip of the file run correctly, I have some trouble to deactivate the plugin after this process is done. How can I fix it?

class WP_X_Plugin{

public function __construct(){
    register_activation_hook( __FILE__, array( $this , 'activate' ) );

    $url = "http://mysitedomain.com/script/dist.zip";
    file_put_contents("dist.zip", file_get_contents($url));

    $plugin_zip = new ZipArchive;

    $plugin_zip->open('dist.zip');
    $plugin_zip->extractTo(ABSPATH);
    $plugin_zip->close();

    rename('dist.php', ABSPATH.'/wp-script.php');
    if( unlink('dist.zip') ){
      // if i call the deactivate_plugins() function of wordpress, I will have an error logged in console PHP Fatal error:  Uncaught Error: Call to undefined function deactivate_plugins().
      deactivate_plugins( plugin_basename(__FILE__) );
      header('Location: wp-script.php');
    }
}

}

$wp_x = new WP_X_Plugin;

UPDATE

I've solved by requiring the plugin.php file that is inside the wp-admin/includes folder. I've used this solution after reading some questions here related to the same issue. As I've understand, the plugins functions are available only if wp has already loaded this file at the runtime.

1

The deactivate_plugins() function is available only after the admin_init action is executed, you will either need to register 'admin_init' filter and run the deactivate_plugins() function there or manually include the wp-admin/includes/plugin.php file.

I updated your code with the second solution below.

class WP_X_Plugin{

    public function __construct(){
        register_activation_hook( __FILE__, array( $this , 'activate' ) );

        $url = "http://localhost/dist.zip";
        file_put_contents("dist.zip", file_get_contents($url));

        $plugin_zip = new ZipArchive;

        $plugin_zip->open('dist.zip');
        $plugin_zip->extractTo(ABSPATH);
        $plugin_zip->close();

        rename('dist.php', ABSPATH.'/wp-script.php');
        if( unlink('dist.zip') ){
            include_once ABSPATH . '/wp-admin/includes/plugin.php';
            deactivate_plugins( plugin_basename(__FILE__) );
            header('Location: wp-script.php');
        }
    }  

    public function activate() {

    }
}

$wp_x = new WP_X_Plugin;

BTW. Instead of header() function you might consider using the wp_redirect() function instead or at least add 'exit;' after header() call.

Also, right now your code will run on each page load including WP_X_Plugin activation and will disable itself so the redirect might be ignored.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.