Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save brianlayman/0f6c79866f17b0e64cf4d35a42787d48 to your computer and use it in GitHub Desktop.
Save brianlayman/0f6c79866f17b0e64cf4d35a42787d48 to your computer and use it in GitHub Desktop.
How to ensure a child theme's style.css is always refreshed when a new style sheet is deployed.
// This gets the modified time for the current style sheet. It caches the check for 30 seconds.
// That's the longest you'd have to wait for a new style sheet to be forced on all visitors.
// This micro-caching helps limit drive access when the site is busy.
// You could change it to 5 seconds on a less busy site or any value you like
function enqueue_versioned_child_style() {
// StyleSheet date is only checked once every 30 seconds
if ( false === ( $stylesheetmtime = get_transient( 'stylesheetmtime' ) ) ) {
// It wasn't there, so regenerate the data and save the transient
$stylesheetmtime = filemtime( get_stylesheet_directory() . '/style.css');
set_transient( 'stylesheetmtime', $stylesheetmtime, 30 );
}
// Version theme's CSS file in a theme
// As long as the handle is the same, you do not need to deregister the style.
wp_enqueue_style(
'roots_child', // This is the handle for the style of a child theme
get_stylesheet_directory_uri() . '/style.css',
array(),
$stylesheetmtime
);
}
add_action( 'wp_enqueue_scripts', 'enqueue_versioned_child_style' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment