Skip to content

Instantly share code, notes, and snippets.

@EricBusch
Last active February 26, 2019 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EricBusch/4f00ff90835da5bd92df33043652303a to your computer and use it in GitHub Desktop.
Save EricBusch/4f00ff90835da5bd92df33043652303a to your computer and use it in GitHub Desktop.
Automatically optimize specific WordPress tables and prune specific rows from the "options" table. Use with caution and with backups in place!
<?php
/**
* Adds a new cron interval to the cron $schedules array.
*
* @param array $schedules
*
* @return array
*/
function mycode_my_custom_cron_schedules( $schedules ) {
if ( ! isset( $schedules['every_five_minutes'] ) ) {
$schedules['every_five_minutes'] = [
'interval' => ( MINUTE_IN_SECONDS * 5 ),
'display' => __( 'Once Every 5 Minutes' ),
];
}
return $schedules;
}
add_filter( 'cron_schedules', 'mycode_my_custom_cron_schedules' );
/**
* Schedules my custom events.
*/
function mycode_schedule_custom_events() {
/** Schedule the "mycode_optimize_tables_event" action hook to be called every 5 minutes. */
if ( ! wp_next_scheduled( 'mycode_optimize_tables_event' ) ) {
wp_schedule_event( time(), 'every_five_minutes', 'mycode_optimize_tables_event' );
}
/** Schedule the "mycode_cleanup_options_table_event" action hook to be called every hour. */
if ( ! wp_next_scheduled( 'mycode_cleanup_options_table_event' ) ) {
wp_schedule_event( time(), 'hourly', 'mycode_cleanup_options_table_event' );
}
}
add_action( 'wp', 'mycode_schedule_custom_events' );
/**
* Optimize table(s)
*/
function mycode_optimize_tables() {
global $wpdb;
$tables = [
'options',
'postmeta',
];
foreach ( $tables as $table ) {
$table_name = $wpdb->prefix . $table;
if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $table_name ) ) === $table_name ) {
$wpdb->query( "OPTIMIZE TABLE $table_name" );
}
}
}
add_action( 'mycode_optimize_tables_event', 'mycode_optimize_tables' );
function mycode_cleanup_options_table() {
global $wpdb;
$options = [
'%_wc_product_loop%', // Plugin: WooCommerce
'%_wc_related%', // Plugin: WooCommerce
'%_wc_loop%', // Plugin: WooCommerce
'%_cache_validator', // Plugin: Yoast SEO
'%ewwwio_media_optimize%', // Plugin: EWWW Image Optimizer
];
foreach ( $options as $option ) {
$query = "DELETE FROM $wpdb->options WHERE option_name LIKE %s";
$wpdb->query( $wpdb->prepare( $query, $option ) );
}
}
add_action( 'mycode_cleanup_options_table_event', 'mycode_cleanup_options_table' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment