0

I've tried looking around but I can't find anything I can understand. I'm quite a newbie when it comes to gulp and stuff, as I mainly use it to automate a couple of tasks for front end dev so I've managed to make it work with the few things I needed (sass, watch, browser-sync), but I now wanted to add imagemin to my gulpfile.js and here comes the issue.

I've been able to make it work with the standard syntax

            // Optimise Images
            gulp.task('imagemin', function() {
               var imgSrc = 'wp-content/themes/solid-theme-child/img/*.+(png|jpg|gif)',
               imgDst = 'wp-content/themes/solid-theme-child/img/opt';

               gulp.src(imgSrc)
               .pipe(changed(imgDst))
               .pipe(imagemin())
               .pipe(gulp.dest(imgDst));
            });

I mainly work with WordPress and I would like to scan the whole /wp-content/uploads folder and its subfolders, but the problem is that I can't define a specific output folder since /uploads/ contains many folders sorted by month, and a new one is being added every month. I would like to scan all of these and optimise the images inside, then replace the original images with their optimised version without creating copies in any specific predefined folder.

Sorry for the dumb question, if I could have figured this out myself I wouldn't have asked but I really don't know how to do it, I hope you understand.

Thank you very much!

Alessandro Benassi
  • 1,640
  • 2
  • 14
  • 19

1 Answers1

0

What you want to use is the glob (**) pattern. It allows you to select files in directories multiple levels down. It's often used together with Gulp.

You can use the same folder name as input to both gulp.src() and gulp.dest(). That will overwrite the original images.

Here is an example that will optimize all the png images in the wp-content/uploads folder. It will step into all the subfolders, pick the png images, optimize them, and write them back to the same folders they were in.

const gulp = require('gulp');
const imagemin = require('gulp-imagemin');
const imageminPngquant = require('imagemin-pngquant');

const imagesDir = 'wp-content/uploads';

gulp.task('compressimages', () => {
  gulp.src(`${imagesDir}/**/*.png`)
    .pipe(imagemin([imageminPngquant({ quality: '30' })]))
    .pipe(gulp.dest(imagesDir));
});

gulp.task('default', ['compressimages']);
Mika Sundland
  • 18,120
  • 16
  • 38
  • 50