Search code examples
htmlcssgulp

Add hash to a filename, then replace references to it using Gulp


I have the file base.css, and I have a styles.php file with the following code:

wp_enqueue_script('base', get_template_directory_uri() . '/css/base.css');

How can I have Gulp rename base.css with its hash and replace the reference in styles.php?

So, I'm looking for the file to be called e.g. base-375dfd5f.css and styles.php to read

wp_enqueue_script('base', get_template_directory_uri() . '/css/base-375dfd5f.css');

Solution

  • You could add a Gulp rename pipe in your stream for the css name, and then use Gulp inject string for the update on the PHP file.

    Something like this should work:

     var gulp   = require('gulp'),
         rename = require('gulp-rename'),
         inject = require('gulp-inject-string');
    
     var myHash = someLogicToGetThisValue();
    
     gulp.task('CSSHash', function () {
            return gulp.src('base.css')
                    .pipe(rename('base' + myHash + '.css'))
                    .pipe(gulp.dest('./')
     });
    
     gulp.task('PHPHashInject', function () {
            return gulp.src('file.php')
                    .pipe(inject.replace('base.css', 'base' + myHash + '.css'))
                    .pipe(gulp.dest('./')
     });