Or, embed this snippet using GenerateWP WordPress Plugin.

Download

Clone

Saotn Database Table Optimizer

Optimizes WordPress database behind the scenes by executing an OPTIMIZE TABLE statement on all MySQL tables, ‘daily’ or ‘hourly’ as a WordPress Cron. More information @ https://www.saotn.org/optimize-wordpress-mysql-tables-cron/
https://gist.github.com/Digiover/b3d33495ba1a400a84068120eb8addbc

/**
 * Plugin Name: Saotn Database Table Optimizer
 * Plugin URI: https://www.saotn.org
 * Description: Optimizes WordPress database behind the scenes by executing an OPTIMIZE TABLE statement on all MySQL tables, 'daily' or 'hourly'. Please <a rel="nofollow" target="_blank" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&amp;hosted_button_id=4EFPSXA623NZA" title="donate to Sysadmins of the North">donate $2.50 USD</a> through PayPal to support me in my research time and hosting costs.
 * Version: 1.0.2
 * Author: Jan Reilink
 * Author URI: https://www.saotn.org
 * License: GPLv2
 */
class Saotn_Db_Optimize_Tables_Cron {
  public static function load() {
    add_action( 'init', array( __CLASS__, 'schedule_events' ) );
  }
  /**
   * Schedule cron events, runs during init.
   */
  public static function schedule_events() {
    if ( ! wp_next_scheduled( 'saotn_db_optimize_tables_cron' ) )
      // wp_schedule_event( time(), 'daily', 'saotn_db_optimize_tables_cron' );
      wp_schedule_event( time(), 'hourly', 'saotn_db_optimize_tables_cron' );
      add_action( 'saotn_db_optimize_tables_cron', array( __CLASS__, 'optimize_tables' ) );
  }
  public static function optimize_tables() {
    global $wpdb;
    $bDebug = TRUE;
    $tables = $wpdb->get_col( "SHOW TABLES" );
    foreach ( $tables as $table ) {
      if ( $wpdb->query( "OPTIMIZE TABLE $table" ) !== FALSE ) {
        if ( $bDebug ) {
          error_log( "Saotn_Db_Optimizer ran successfully on $table" );
        }
      }
    }
  }
}
Saotn_Db_Optimize_Tables_Cron::load();