Develop WordPress Themes Faster with Gulp

Share this article

Speed - by Alex Walker (recalling the ace old Maxel Tape ads).

This Gulp article is part of a series created in partnership with SiteGround. Thank you for supporting the partners who make SitePoint possible.

WordPress’ simple theme development is partly responsible for its success. A developer with front-end and PHP knowledge can consult the excellent Codex and get started on their next masterpiece.

Theme development is possible with just a text editor and graphics package, but modern toolsets can revolutionize your workflow. In this tutorial we’ll use Gulp to run tasks including:

  • copying newer PHP theme files
  • optimizing images
  • compiling Sass SCSS files into a single, minified CSS file
  • merging ordered JavaScript files, remove debugging statements and minifying
  • automatically refreshing the browser when files are updated.

What is Gulp?

Gulp is a JavaScript-based build system which takes your source files and transforms them into optimized versions. If you’re new to Gulp, please refer to An Introduction to Gulp.js for full installation and usage instructions. A summary of the initial steps:

  1. Install Node.js.
  2. Install Gulp globally: npm install gulp-cli -g
  3. Create a project folder and navigate into it: mkdir mytheme followed by cd mytheme.
  4. Initialize your project with npm: npm init

Your Project Files

A Gulp (or any) build process requires a set of original source files containing your unmodified code and images. These are processed, manipulated and minified to create build files.

WordPress is installed to a web server folder, perhaps /var/www/ on a Linux/Apache installation. Your WordPress theme must be defined in its own sub-folder within /wp-content/themes/. Therefore, the folder containing our built files could be /var/www/wp-content/themes/mytheme/. At a minimum, themes require two files:

  • a style.css stylesheet containing meta-data in comments at the top, and
  • an index.php template file.

Most themes contain many more files for presenting posts, pages, indexes, categories, tags, and errors. Cross-page partials such as headers and footers are usually defined as are image and JavaScript files.

You could place your source files somewhere within the mytheme folder. That may be useful if you’re distributing a theme to be downloaded, modified and built by others. However, for the purpose of this tutorial, we’re going to use a source folder which is inaccessible from the web server, e.g. ~/mytheme/. The benefits of this approach:

  1. Your theme source files can be managed in a single folder and repository without polluting the build or WordPress folders.
  2. The final built theme folder contains only the files it requires.
  3. Gulp, its plug-ins and other applications are not contained in the theme folder. They cannot be accidentally copied to a production server which is unnecessary and could have security implications.

The source project folder requires a further four sub-folders:

  • template – the WordPress PHP theme files
  • images – images used by your theme
  • scss – Sass SCSS source files
  • js – any number of separate client-side JavaScript source files.

Install Dependencies

From the source folder (~/mytheme/), run the following npm command to install Gulp and all plug-ins as development dependencies:

npm install --save-dev autoprefixer browser-sync css-mqpacker cssnano gulp gulp-concat gulp-deporder gulp-imagemin gulp-newer gulp-postcss gulp-sass gulp-strip-debug gulp-uglify gulp-util postcss-assets

A node_modules folder will be created which contains the module code. That should be omitted from your source control system (for Git users, add node_modules to your .gitignore file).

Create a Gulp Configuration File

Create a new gulpfile.js configuration file in the root of your source folder. Add this code to get started:

// Gulp.js configuration
'use strict';


  // source and build folders
  dir = {
    src         : 'src/',
    build       : '/var/www/wp-content/themes/mytheme/'

  // Gulp and plugins
  gulp          = require('gulp'),
  gutil         = require('gulp-util'),
  newer         = require('gulp-newer'),
  imagemin      = require('gulp-imagemin'),
  sass          = require('gulp-sass'),
  postcss       = require('gulp-postcss'),
  deporder      = require('gulp-deporder'),
  concat        = require('gulp-concat'),
  stripdebug    = require('gulp-strip-debug'),
  uglify        = require('gulp-uglify')

// Browser-sync
var browsersync = false;

// PHP settings
const php = {
  src           : dir.src + 'template/**/*.php',
  build         :

// copy PHP files
gulp.task('php', () => {
  return gulp.src(php.src)

We’re defining our default folders, loading modules, then creating a php task to copy new and updated files to the theme folder. The task has been kept intentionally simple to copy the PHP source files as-is.

Save gulpfile.js and create a few .php files in the source template folder. Then enter the following command:

gulp php

All the files will be copied to the theme folder (/var/www/wp-content/themes/mytheme/).

Image Processing

Image files can often be compressed further using tools such as imagemin. Add the following code to gulpfile.js:

// image settings
const images = {
  src         : dir.src + 'images/**/*',
  build       : + 'images/'

// image processing
gulp.task('images', () => {
  return gulp.src(images.src)

Save then run gulp images. Compressed versions of any new or updated images in the source images folder are copied to /var/www/wp-content/themes/mytheme/images/.

Sass Compilation

WordPress cannot use Sass files directly; you must compile to a single style.css file. Add the following code to gulpfile.js:

// CSS settings
var css = {
  src         : dir.src + 'scss/style.scss',
  watch       : dir.src + 'scss/**/*',
  build       :,
  sassOpts: {
    outputStyle     : 'nested',
    imagePath       :,
    precision       : 3,
    errLogToConsole : true
  processors: [
      loadPaths: ['images/'],
      baseUrl: '/wp-content/themes/wptheme/'
      browsers: ['last 2 versions', '> 2%']

// CSS processing
gulp.task('css', ['images'], () => {
  return gulp.src(css.src)
    .pipe(browsersync ? browsersync.reload({ stream: true }) : gutil.noop());

Launch this new task with gulp css to:

  • run the Gulp images task first (images may be required in your CSS)
  • compile the Sass code in the source scss/style.scss file using the fast LibSass compiler
  • use PostCSS to automatically add asset references, apply vendor prefixes, pack media queries together, and minify the resulting CSS code
  • output the stylesheet to /var/www/wp-content/themes/mytheme/style.css.
  • force a Browsersync CSS reload (more about that later).

The source scss/style.scss file must include the WordPress theme meta data at the top, e.g.

    Theme Name: My Theme
    Theme URI:
    Description: Demonstration theme
    Version: 1.0.0
    Author: Craig Buckler (@craigbuckler)
    Author URI:
    Tags: Gulp

    License: MIT
    License URI:

@import '_base';
@import '_forms';
@import '_tables';
@import 'components/_widget1';
// etc...

It is important to use /*! as the first line. This ensures the cssnano minifier does not remove the comment and render your theme unusable.

The postcss-assets plugin allows you to refer to image assets using code such as:

.widget1 {
  width: width('myimage.jpg');
  height: height('myimage.jpg');
  background-image: resolve('myimage.jpg');

You can also inline images with automatic Base64 encoding:

.widget2 {
  background-image: inline('myimage.jpg');

JavaScript Processing

Add the following code to gulpfile.js:

// JavaScript settings
const js = {
  src         : dir.src + 'js/**/*',
  build       : + 'js/',
  filename    : 'scripts.js'

// JavaScript processing
gulp.task('js', () => {

  return gulp.src(js.src)
    .pipe(browsersync ? browsersync.reload({ stream: true }) : gutil.noop());


Run this new task with gulp js to:

  • process all JavaScript files in the source js folder
  • order the files appropriately. Add comments at the top of your JavaScript files to declare dependencies, e.g. // requires: lib1.js or // requires: config.js lib1.js.
  • concatenate into a single file
  • strip all debugging and console logging statements
  • minify the code
  • output the resulting code to /var/www/wp-content/themes/mytheme/js/scripts.js.
  • force a Browsersync CSS reload (more about that later).

Run Everything

Rather than calling each task separately, we can add the following code to gulpfile.js:

// run all tasks
gulp.task('build', ['php', 'css', 'js']);

You can now use gulp build to run the php, js, css and images tasks in parallel. (Note images is a dependency of the css task so we need not call it directly.)

Enable File Watching and Browsersync

Your workflow can be radically improved by:

  1. Letting Gulp watch for file changes before launching the appropriate task.
  2. Automatically reloading CSS and JavaScript files when they change (without a page refresh).
  3. Automatically refreshing the page when a template file changes.

First, we need to define a browsersync task in gulpfile.js. This will create a proxy server to your web server running WordPress on localhost (change this domain or use an IP address as necessary):

// Browsersync options
const syncOpts = {
  proxy       : 'localhost',
  files       : + '**/*',
  open        : false,
  notify      : false,
  ghostMode   : false,
  ui: {
    port: 8001

// browser-sync
gulp.task('browsersync', () => {
  if (browsersync === false) {
    browsersync = require('browser-sync').create();

Now add a watch task to run Browsersync, watch for file changes and run the appropriate task:

// watch for file changes
gulp.task('watch', ['browsersync'], () => {

  // page changes, ['php'], browsersync ? browsersync.reload : {});

  // image changes, ['images']);

    // CSS changes, ['css']);

  // JavaScript main changes, ['js']);


Finally, add a default Gulp task which runs an initial build and starts the watch task:

// default task
gulp.task('default', ['build', 'watch']);

Now run gulp from the command line. The console will display output which includes lines similar to:

[BS] Proxying: http://localhost
[BS] Access URLs:
       Local: http://localhost:3000
          UI: http://localhost:8001
 UI External:
[BS] Watching files...

Rather than loading your development site from http://localhost/, enter the address http://localhost:3000/ or the External URL if you are viewing from another device. Your WordPress site will load as before but Gulp will watch for changes and apply the updates immediately. You’ll need never switch to your browser and click refresh again!

Hit Ctrl/Cmd + C when you want to stop Gulp processing.

Enhance Further

We’ve covered the basics of WordPress theme development with Gulp but there are several thousand plug-ins to aid your workflow. You could consider additional tasks to:

A few hours writing Gulp tasks could save many days of manual processing over the long term.

Frequently Asked Questions (FAQs) about Gulp WordPress Theme Development Workflow

What is the role of Gulp in WordPress theme development?

Gulp is a task runner that automates repetitive tasks in the development process, such as minification, compilation, unit testing, linting, etc. It uses a code-over-configuration approach, making it flexible and easy to use. In WordPress theme development, Gulp can be used to automate tasks like compiling Sass to CSS, optimizing images, and refreshing the browser whenever a file is saved. This significantly speeds up the development process and ensures a smooth workflow.

How do I install Gulp for WordPress theme development?

To install Gulp, you first need to have Node.js and npm installed on your system. Once you have these, you can install Gulp globally by running the command npm install --global gulp-cli in your terminal. After that, navigate to your WordPress theme directory and run npm init to create a package.json file. Finally, install Gulp in your project devDependencies by running npm install --save-dev gulp.

How do I set up a Gulpfile for my WordPress theme?

A Gulpfile is a JavaScript file that defines the tasks that Gulp will run. To set up a Gulpfile, create a new file in your theme directory named gulpfile.js. Inside this file, you can define tasks using the gulp.task method. For example, a task to compile Sass to CSS might look like this:

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', function() {
return gulp.src('src/scss/**/*.scss')

How can I use Gulp to optimize images in my WordPress theme?

Gulp can be used to optimize images using plugins like gulp-imagemin. To do this, first install the plugin by running npm install --save-dev gulp-imagemin. Then, create a task in your Gulpfile to optimize images:

var gulp = require('gulp');
var imagemin = require('gulp-imagemin');

gulp.task('images', function() {
return gulp.src('src/images/**/*')

How can I use Gulp to automatically refresh the browser when I save a file?

Gulp can be used to automatically refresh the browser using plugins like BrowserSync. To do this, first install BrowserSync by running npm install --save-dev browser-sync. Then, create a task in your Gulpfile to start a BrowserSync server:

var gulp = require('gulp');
var browserSync = require('browser-sync').create();

gulp.task('serve', function() {
proxy: ''
});'src/**/*').on('change', browserSync.reload);

Replace ‘’ with your local development URL.

How can I use Gulp to compile JavaScript files in my WordPress theme?

Gulp can be used to compile JavaScript files using plugins like gulp-babel. To do this, first install the plugin by running npm install --save-dev gulp-babel @babel/core @babel/preset-env. Then, create a task in your Gulpfile to compile JavaScript:

var gulp = require('gulp');
var babel = require('gulp-babel');

gulp.task('js', function() {
return gulp.src('src/js/**/*.js')
presets: ['@babel/env']

How can I use Gulp to minify CSS and JavaScript files in my WordPress theme?

Gulp can be used to minify CSS and JavaScript files using plugins like gulp-clean-css and gulp-uglify. To do this, first install the plugins by running npm install --save-dev gulp-clean-css gulp-uglify. Then, create tasks in your Gulpfile to minify CSS and JavaScript:

var gulp = require('gulp');
var cleanCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');

gulp.task('minify-css', function() {
return gulp.src('dist/css/**/*.css')

gulp.task('minify-js', function() {
return gulp.src('dist/js/**/*.js')

How can I use Gulp to lint JavaScript files in my WordPress theme?

Gulp can be used to lint JavaScript files using plugins like gulp-eslint. To do this, first install the plugin by running npm install --save-dev gulp-eslint. Then, create a task in your Gulpfile to lint JavaScript:

var gulp = require('gulp');
var eslint = require('gulp-eslint');

gulp.task('lint', function() {
return gulp.src('src/js/**/*.js')

How can I use Gulp to run all tasks at once in my WordPress theme?

Gulp can be used to run all tasks at once using the gulp.series or gulp.parallel methods. To do this, create a task in your Gulpfile to run all tasks:

var gulp = require('gulp');

gulp.task('default', gulp.series('sass', 'images', 'serve', 'js', 'minify-css', 'minify-js', 'lint'));

How can I use Gulp to watch for changes in my WordPress theme?

Gulp can be used to watch for changes using the method. To do this, create a task in your Gulpfile to watch for changes:

var gulp = require('gulp');

gulp.task('watch', function() {'src/scss/**/*.scss', gulp.series('sass'));'src/images/**/*', gulp.series('images'));'src/js/**/*.js', gulp.series('js', 'lint'));

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week