Skip to content

Instantly share code, notes, and snippets.

@apermo
Last active July 3, 2019 05:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apermo/0c874200c5b0016eb3851ae2739a0f5b to your computer and use it in GitHub Desktop.
Save apermo/0c874200c5b0016eb3851ae2739a0f5b to your computer and use it in GitHub Desktop.
wrapper for wp_enqueue_style using filemtime
<?php
// has been taken from a class, globals are just a quick and dirty workarround
// This Wrapper is one example for a simple use of cached filemtime version strings, in this case for the parent theme.
// Needs small changes to work for childtheme, javascript, plugins or register
function local_enqueue_style( $handle, $src, $deps = array(), $media = 'all' ) {
wp_enqueue_style( $handle, get_template_directory_uri() . $src, $deps, local_get_version( get_template_directory() . $src ), $media );
}
function local_get_version( $filepath ) {
//see line 2
global $file_versions;
if ( ! is_array( $file_versions ) ) {
if ( ! defined( 'NO_CACHING' ) || ! NO_CACHING ) {
$file_versions = get_transient( 'file_versions' );
}
if ( ! is_array( $file_versions ) ) {
$file_versions = array();
}
}
$hash = md5( $filepath );
if ( ! isset( $file_versions[ $hash ] ) ) {
//see line 2
global $update_file_versions;
$update_file_versions = true;
if ( file_exists( $filepath ) ) {
$file_versions[ $hash ] = filemtime( $filepath );
} else {
return 'fnf'; //file not found
}
}
return $file_versions[ $hash ];
}
add_action( 'shutdown', 'save_file_versions' );
function save_file_versions() {
//see line 2
global $update_file_versions, $file_versions;
if ( $update_file_versions ) {
set_transient( 'file_versions', $file_versions, 3600 );
}
}
@Ridder90
Copy link

Very intresting! I was wondering why you used md5 for hashing the keys ?

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