Home > Dev > WordPress Optimization > Automatic Database Optimization

Automatic Database Optimization

This code will schedule a daily database optimization.

// Add this to your theme's functions.php file

if (!wp_next_scheduled('automatic_database_optimization')) {
    wp_schedule_event(time(), 'daily', 'automatic_database_optimization');
}

add_action('automatic_database_optimization', 'optimize_database');

function optimize_database() {
    global $wpdb;
    $wpdb->query('OPTIMIZE TABLE ' . $wpdb->prefix . 'posts');
    $wpdb->query('OPTIMIZE TABLE ' . $wpdb->prefix . 'postmeta');
    $wpdb->query('OPTIMIZE TABLE ' . $wpdb->prefix . 'comments');
    $wpdb->query('OPTIMIZE TABLE ' . $wpdb->prefix . 'commentmeta');
    $wpdb->query('OPTIMIZE TABLE ' . $wpdb->prefix . 'options');
    $wpdb->query('OPTIMIZE TABLE ' . $wpdb->prefix . 'usermeta');
    $wpdb->query('OPTIMIZE TABLE ' . $wpdb->prefix . 'users');
}
Back