Skip to content

Instantly share code, notes, and snippets.

@Digiover
Last active April 15, 2019 15:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Digiover/b3d33495ba1a400a84068120eb8addbc to your computer and use it in GitHub Desktop.
Save Digiover/b3d33495ba1a400a84068120eb8addbc to your computer and use it in GitHub Desktop.
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/
<?php
/**
* 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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment