Site Health Check for Compression and Browser Caching
Adds a Site Health test that requests your homepage and one of your theme's stylesheets and reports whether text files are compressed (gzip or Brotli) and whether static files get long browser cache lifetimes.
Opens WPIDE on
Code
add_filter( 'site_status_tests', function ( $tests ) {
$tests['direct']['wpide_compression_cache'] = array(
'label' => 'Compression and browser caching',
'test' => function () {
$result = get_transient( 'wpide_compression_check' );
if ( false === $result ) {
$args = array( 'timeout' => 8, 'sslverify' => apply_filters( 'https_local_ssl_verify', false ), 'headers' => array( 'Accept-Encoding' => 'gzip, br' ), 'decompress' => false );
$home = wp_remote_get( home_url( '/' ), $args );
$css = wp_remote_get( get_stylesheet_uri(), $args );
$cc = (string) wp_remote_retrieve_header( $css, 'cache-control' );
$age = preg_match( '/max-age=(\d+)/', $cc, $m ) ? (int) $m[1] : 0;
$result = array(
'compressed' => ! is_wp_error( $home ) && '' !== (string) wp_remote_retrieve_header( $home, 'content-encoding' ),
'cached' => ! is_wp_error( $css ) && ( $age >= 30 * DAY_IN_SECONDS || '' !== (string) wp_remote_retrieve_header( $css, 'expires' ) ),
'error' => is_wp_error( $home ),
);
set_transient( 'wpide_compression_check', $result, 12 * HOUR_IN_SECONDS );
}
$problems = array();
if ( ! $result['compressed'] ) {
$problems[] = 'pages are not compressed with gzip or Brotli';
}
if ( ! $result['cached'] ) {
$problems[] = 'static files such as CSS do not have a long browser cache lifetime';
}
return array(
'label' => $result['error'] ? 'Compression and caching could not be checked' : ( $problems ? 'Compression or browser caching is missing' : 'Compression and browser caching are enabled' ),
'status' => $problems ? 'recommended' : 'good',
'badge' => array( 'label' => 'Performance', 'color' => 'blue' ),
'description' => '<p>' . esc_html( $problems ? 'Your server reports that ' . implode( ' and ', $problems ) . '. Ask your host to enable compression and long cache headers for static files.' : 'Text responses are compressed and static files are cached by browsers.' ) . '</p>',
'test' => 'wpide_compression_cache',
);
},
);
return $tests;
} );
Notes
Both are configured in your web server or CDN, not in WordPress; the result is cached for 12 hours.
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.