How to Build a WordPress Project Using a Custom Theme, Building Assets with NPM

When developing a custom WordPress theme, using npm (Node Package Manager) to handle your theme assets can drastically streamline your development process. This tutorial will walk you through the steps of setting up a WordPress project, creating a custom theme, and using npm to manage and build your assets such as CSS, JavaScript, and images.

If you’ve read this far, you’re probably a DeployBot user and familiar with version control systems, CI/CD, and other related topics. If not, we’ve compiled several beginner’s guides: Laravel, Digital Ocean, Ruby on Rails, Docker, Craft CMS, Ghost CMS, Google Web Starter Kit, Grunt or Gulp, Slack, Python, Heroku and many more.

Learn how to get started with DeployHQ here.

Prerequisites

  • A local development environment with PHP, MySQL, and Apache/Nginx. Tools like MAMP, XAMPP, or LocalWP can be used.
  • Node.js and npm installed on your local machine.
  • A code editor of your choice (e.g., Visual Studio Code, Sublime Text).
  • Basic knowledge of WordPress theme structure and PHP.

Step 1: Setting Up Your WordPress Environment

  1. Download and Install WordPress:
    • Download the latest version of WordPress from the official website.
    • Create a new database and user for your WordPress installation using a tool like phpMyAdmin.
    • Install WordPress by placing the downloaded files into your local server's web directory, running the WordPress installation script, and following the instructions.
  2. Set Up a Virtual Host (optional):
    • If you're using MAMP, XAMPP, or similar, configure a virtual host for your project for a cleaner URL (e.g., http://mywordpress.test).

Step 2: Creating Your Custom Theme

  1. Create a Theme Directory:
    • Navigate to wp-content/themes within your WordPress installation.
    • Create a new directory for your theme, such as mycustomtheme.
  2. Add Basic Theme Files:
    • Inside your theme folder, create the necessary WordPress theme files:
      • style.css - Add the required theme headers at the top of the file.
      • index.php - The main fallback template file for WordPress.
      • functions.php - Where you'll add functionality and enqueue your styles and scripts.
      • Other files as needed for your theme structure (e.g., header.phpfooter.phpsingle.php, etc.)
  3. Activate Your Theme:
    • In the WordPress admin dashboard, navigate to Appearance > Themes and activate your custom theme.

Step 3: Initializing NPM in Your Theme

  1. Open a Terminal:
    • Navigate to your custom theme's directory in the command line.
  2. Initialize a New NPM Project:
    • Run npm init and follow the prompts to create a package.json file.

Step 4: Installing Asset Build Tools with NPM

  1. Install Development Tools:
    • For this tutorial, we'll use Sass for styling and Webpack for asset bundling.
    • Install the required npm packages by running:
      npm install --save-dev webpack webpack-cli sass node-sass css-loader sass-loader mini-css-extract-plugin clean-webpack-plugin
      

  2. Configure Webpack:
    • Create a file named webpack.config.js in your theme directory.
    • Set up the configurations for processing your Sass files and any JavaScript.

Example webpack.config.js:

const path = require('path'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin');  module.exports = {   entry: './src/index.js',   output: {     path: path.resolve(__dirname, 'dist'),     filename: 'bundle.js',   },   module: {     rules: [       {         test: /\.scss$/,         use: [           MiniCssExtractPlugin.loader,           'css-loader',           'sass-loader',         ],       },     ],   },   plugins: [     new CleanWebpackPlugin(),     new MiniCssExtractPlugin({       filename: 'style.css',     }),   ], };
  1. Create Source Directories:
    • Inside your theme, create a src directory for your Sass and JavaScript source files.
    • Create an entry point index.js in src and import your main Sass file.

Example src/index.js:

import './scss/main.scss'; // You can also import JS modules here if needed.

Step 5: Building Your Assets

  1. Configure NPM Scripts:
    • Modify the scripts section in your package.json to include a build command.
"scripts": {   "build": "webpack --mode production" },
  1. Run the Build Command:
    • Execute npm run build to compile your assets. This will create a dist folder in your theme with the built assets.

Step 6: Enqueuing Theme Assets in WordPress

  1. Update functions.php:
    • Enqueue the built CSS and JavaScript in your theme's functions.php file.

Example functions.php:

<?php function my_custom_theme_scripts() {     wp_enqueue_style('my-custom-theme-styles', get_template_directory_uri() . '/dist/style.css');     wp_enqueue_script('my-custom-theme-scripts', get_template_directory_uri() . '/dist/bundle.js', array(), false, true); } add_action('wp_enqueue_scripts', 'my_custom_theme_scripts');

Conclusion

You now have a WordPress project running with a custom theme that builds its assets using npm and modern tooling. This setup can be expanded further to include tools like Babel for JavaScript transpilation, ESLint for code quality, and PostCSS for advanced CSS processing.

By managing your theme assets with npm, you gain the advantage of using a vast ecosystem of packages and a build process that enhances performance, modularity, and maintainability of your WordPress theme development.