Skip to content

Instantly share code, notes, and snippets.

@kylehotchkiss
Created April 27, 2014 04:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylehotchkiss/e994a699f9541a7ea038 to your computer and use it in GitHub Desktop.
Save kylehotchkiss/e994a699f9541a7ea038 to your computer and use it in GitHub Desktop.
CDNify for Grunt/Wordpress - Failsafe code for conditionally using versioned CDN'd assets with wordpress, fails back to local files.
md5: {
compile: {
files: {
'<%= config.tmp %>/styles/': '<%= config.wordpress %>/**/*.css',
'<%= config.tmp %>/scripts/': '<%= config.wordpress %>/**/*.js'
},
options: {
keepBasename: true,
keepExtension: true,
after: function ( changes ) {
var php = '<?php\n $cdnifyMap = [';
changes.forEach(function( change ) {
var newFile = change.newPath.replace(/^.*[\\\/]/, '');
var oldFile = change.oldPath.replace(/^.*[\\\/]/, '');
php += '\n "' + oldFile + '" => "' + newFile + '",';
});
php += '\n ];\n?>';
grunt.file.write("wordpress/wp-content/themes/timber/assets.php", php);
}
}
}
},
compress: {
wordpress: {
options: {
mode: 'gzip'
},
files: [
{ expand: true, cwd: '<%= config.tmp %>/', src: ['**/*.js'], dest: '<%= config.launch %>/', ext: ".js" },
{ expand: true, cwd: '<%= config.tmp %>/', src: ['**/*.css'], dest: '<%= config.launch %>/', ext: ".css" }
]
}
},
s3: {
options: {
key: "",
secret: "",
bucket: "",
access: "public-read",
headers: {
"Cache-Control": "max-age=315360000, public",
"Expires": new Date(Date.now() + 31536000000).toUTCString()
}
},
wordpress: {
upload: [
{ src: "<%= config.launch %>/fonts/*", dest: "wordpress/fonts/" },
{ src: "<%= config.launch %>/images/*", dest: "wordpress/images/" },
{ src: "<%= config.launch %>/styles/*", dest: "wordpress/styles/", options: {
headers: {
"Content-Encoding": "gzip",
"Cache-Control": "max-age=315360000, public",
"Expires": new Date(Date.now() + 31536000000).toUTCString()
}
}},
{ src: "<%= config.launch %>/scripts/*", dest: "wordpress/scripts/", options: {
headers: {
"Content-Encoding": "gzip",
"Cache-Control": "max-age=315360000, public",
"Expires": new Date(Date.now() + 31536000000).toUTCString()
}
}}
]
}
}
<link href="{{ function("cdnify", "screen.css", "styles") }}" rel="stylesheet" />
<script src="{{ function("cdnify", "main.js", "scripts") }}"></script>
<?php
//
// CDN Support
//
include "assets.php";
function cdnify( $asset, $type ) {
$cdnBase = "//dbkkl7i25qbd9.cloudfront.net/wordpress/";
$lclBase = "/wp-content/themes/timber/assets/";
global $cdnifyMap;
if ( isset($cdnifyMap[ $asset ]) ) {
return $cdnBase . $type . "/" . $cdnifyMap[ $asset ];
} else {
return $lclBase . $type . "/" . $asset;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment