Prevent CSS Caching with filemtime()

Lately, I’ve been having caching issues when trying to amend some CSS on various sites. In fact, this has plagued me for quite a while. I would usually force a page to reload regardless of the cached content or use a common hack such as renaming the file to something like style-v2.css. However, since moving hosts to AWS even this seems not to give me the most recent version.

The following is a method that always serves the newest file each time the page reloads. The filemtime() function returns the last time the file was changed as a Unix timestamp.

// Enqueue custom styles
function enqueue_custom_styles() {
    wp_enqueue_style( 'custom-style', get_stylesheet_directory_uri() . '/custom.css', array(), filemtime( get_stylesheet_directory() . '/custom.css' ), 'all');
add_action( 'wp_enqueue_scripts', 'enqueue_custom_styles', 99 );

More information about filemtime() can be found in the PHP documentation here.