Leverage browser caching not working after updating .htaccess

I have website in WordPress and I updated my .htaccess file with following rule.

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
</IfModule>

Now, when I checked my website performance with Google insight. it still giving me error for leverage browser caching

I have used this code

    add_filter( 'script_loader_src', 'elated_child__remove_ver' );
    add_filter( 'style_loader_src', 'elated_child__remove_ver' );

    function elated_child__remove_ver( $src ) { // Remove query strings from static resources
        if ( strpos( $src, '?f=" ) || strpos( $src, "&f=" ) ) {
            $src = remove_query_arg( "f', $src );
        }



   return $src;
}

Any idea?

3 Answers
3

This should do it

if ( !is_admin() || !is_admin_bar_showing() ){
  add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
  add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );
}

function _remove_script_version( $src ){
  if (preg_match("(\?ver=)", $src )){
    $parts = explode( '?', $src );
    return $parts[0];
  }else{
    return $src;
  }
}

This will remove the ?ver= from the file url. There’s a conditional check to see if we are on an admin page or if we are logged in. In that case, we don’t apply the filters (might be useful information when you work on your site).

Also note that this won’t remove ALL query strings since some plugins/themes might add their own and would use other filters or hardcode it within their code base. But you could hook that same function to those filters if they are provided (if not, you would need to edit those files manually)

For instance, you can add add_filter( 'genesis-header', '_remove_script_version', 15, 1); to that filter list if you were using a genesis theme.

Leave a Comment