Use WP Smush without slowing down WordPress

I use WP Smush to compress images in WordPress. But lately the plugin became extremely slow because of excessive database queries. The media library takes 10 seconds to open while the plugin is active but takes only 2 seconds when it’s inactive. That’s huge..! 🥱

Search in media library became slow, uploading media became slow, anything related to media became slow as duck. 🥴

I tried unhooking some of actions & filters but that wasn’t enough. So I thought of a different approach.

Here’s what I did:

  1. Disabled “Auto Smush on Upload” feature.
  2. Keep WP Smush plugin disabled all the time.
  3. Active the plugin then Smush images using WP-CLI.
  4. Deactivate the plugin again.

The following PHP script enable WP Smush plugin then smush all images then deactivate the plugin.

$path = '--path=/full/path/to/wordpress';

//catch errors using '2>&1'
$output = shell_exec("wp plugin activate wp-smush-pro $path 2>&1");

//if plugin successfully actives 
if (strpos($output, 'Success:') !== false) {
    //smush all non-smushed images
    exec("wp smush compress $path");
    //now deactivate the plugin
    exec("wp plugin deactivate wp-smush-pro $path");

Now WordPress won’t be slow while using the plugin. Setup a cronjob and call the script every day.

I don’t to know how to create bash script that is why I used PHP. Anyone can give me a bash version of this are very much welcome.