Skip to content

Instantly share code, notes, and snippets.

@denvers
Created April 20, 2017 08:01
Show Gist options
  • Save denvers/526878d5f30dfec5650523d1b1225adb to your computer and use it in GitHub Desktop.
Save denvers/526878d5f30dfec5650523d1b1225adb to your computer and use it in GitHub Desktop.
Use this simple WordPress function to avoid browser cache issues after updating your CSS / JS assets. Each time you update your assets the URL will change to force browsers to re-download your asset. Yeah, dab!
<?php
// add to functions.php
/**
* cache_proof_asset_url
* @param string $asset_file (relative, eg: /css/style.css)
* @return string $asset_file_url (absolute, eg: https://www.domain.com/css/style.css?v=123456789)
*/
function cache_proof_asset_url($asset_file) {
$full_asset_url = bloginfo('stylesheet_directory') . $asset_file;
$full_asset_file = get_stylesheet_directory() . $asset_file;
return sprintf("%s?v=%s", $full_asset_url, filemtime($full_asset_file) );
}
?>
<!-- use in your header.php / footer.php -->
<link rel="stylesheet" type="text/css" href="<?php echo cache_proof_asset_url('/css/style.css'); ?>">
@nweevers
Copy link

Simple but effective 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment