Email Alert When Disk Space Runs Low
Checks free disk space on the server twice a day and emails the admin when it drops below your threshold, before uploads, backups and the database start failing.
Opens WPIDE on
Code
$wpide_min_free_gb = 2;
add_action( 'init', function () {
if ( ! wp_next_scheduled( 'wpide_disk_space_check' ) ) {
wp_schedule_event( time() + HOUR_IN_SECONDS, 'twicedaily', 'wpide_disk_space_check' );
}
} );
add_action( 'wpide_disk_space_check', function () use ( $wpide_min_free_gb ) {
if ( ! function_exists( 'disk_free_space' ) || get_transient( 'wpide_disk_alert_sent' ) ) {
return;
}
$free = @disk_free_space( ABSPATH ); // phpcs:ignore WordPress.PHP.NoSilencedErrors
if ( false === $free || $free >= $wpide_min_free_gb * GB_IN_BYTES ) {
return;
}
set_transient( 'wpide_disk_alert_sent', 1, DAY_IN_SECONDS );
wp_mail(
get_option( 'admin_email' ),
sprintf( '[%s] Low disk space: %s free', wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ), size_format( $free ) ),
sprintf( "The server hosting %s has only %s of free disk space left (alert threshold: %d GB).\n\nClear old backups, logs or unused media, or ask your host for more space.", home_url(), size_format( $free ), $wpide_min_free_gb )
);
} );
Notes
Does nothing on hosts that disable disk_free_space(), and repeats the alert at most once a day while space stays low.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.