WordPressをViteで開発できるようにし、Gitで管理する方法

2025.06.02 BLOG

Wordpressと最新の技術の両立を目指した手法を紹介します

はじめに

普段はLaravelで開発しているが、WordPressのプロジェクトを受注することになりました。WordPressの開発経験は少ないため、Laravelの開発環境と同様のセットアップを目指して構築を進めたいと思います。Laravelでは sail を使うことで簡単に環境構築ができるが、WordPressでも同様の開発体験を実現したいと思い今回の方法をメモ代わりに残しておきます。

WordPressの環境をDockerで構築する

WordPressをスクリプトでインストールする

以下のようなスクリプトを作成し、Laravelの laravel new のように簡単にWordPressをインストールできるようにします。

wp-new スクリプト

#!/bin/bash

PROJECT_NAME=$1

if [ -z "$PROJECT_NAME" ]; then
  echo "プロジェクト名を指定してください。"
  exit 1
fi

mkdir "$PROJECT_NAME" && cd "$PROJECT_NAME"

cat <<EOF > docker-compose.yml
version: '3.8'

services:
  wordpress:
    image: wordpress:latest
    container_name: ${PROJECT_NAME}-wordpress
    ports:
      - "80:80"
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: wordpress
      WORDPRESS_DB_NAME: wordpress
    volumes:
      - ./wp-content:/var/www/html/wp-content
      - ./wp-config.php:/var/www/html/wp-config.php

  db:
    image: mysql:5.7
    container_name: ${PROJECT_NAME}-db
    environment:
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - db_data:/var/lib/mysql

  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: ${PROJECT_NAME}-phpmyadmin
    restart: always
    ports:
      - "8888:80"
    environment:
      PMA_HOST: db
      MYSQL_ROOT_PASSWORD: root

volumes:
  db_data:
EOF

# wp-config.php を作成
cat <<EOF > wp-config.php
<?php
/**
 * The base configuration for WordPress
 *
 * The wp-config.php creation script uses this file during the installation.
 * You don't have to use the web site, you can copy this file to "wp-config.php"
 * and fill in the values.
 *
 * This file contains the following configurations:
 *
 * * Database settings
 * * Secret keys
 * * Database table prefix
 * * ABSPATH
 *
 * This has been slightly modified (to read environment variables) for use in Docker.
 *
 * @link https://wordpress.org/support/article/editing-wp-config-php/
 *
 * @package WordPress
 */

// IMPORTANT: this file needs to stay in-sync with https://github.com/WordPress/WordPress/blob/master/wp-config-sample.php
// (it gets parsed by the upstream wizard in https://github.com/WordPress/WordPress/blob/f27cb65e1ef25d11b535695a660e7282b98eb742/wp-admin/setup-config.php#L356-L392)

// a helper function to lookup "env_FILE", "env", then fallback
if (!function_exists('getenv_docker')) {
	// https://github.com/docker-library/wordpress/issues/588 (WP-CLI will load this file 2x)
	function getenv_docker($env, $default) {
		if ($fileEnv = getenv($env . '_FILE')) {
			return rtrim(file_get_contents($fileEnv), "\r\n");
		}
		else if (($val = getenv($env)) !== false) {
			return $val;
		}
		else {
			return $default;
		}
	}
}

// ** Database settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', getenv_docker('WORDPRESS_DB_NAME', 'wordpress') );

/** Database username */
define( 'DB_USER', getenv_docker('WORDPRESS_DB_USER', 'example username') );

/** Database password */
define( 'DB_PASSWORD', getenv_docker('WORDPRESS_DB_PASSWORD', 'example password') );

/**
 * Docker image fallback values above are sourced from the official WordPress installation wizard:
 * https://github.com/WordPress/WordPress/blob/f9cc35ebad82753e9c86de322ea5c76a9001c7e2/wp-admin/setup-config.php#L216-L230
 * (However, using "example username" and "example password" in your database is strongly discouraged.  Please use strong, random credentials!)
 */

/** Database hostname */
define( 'DB_HOST', getenv_docker('WORDPRESS_DB_HOST', 'mysql') );

/** Database charset to use in creating database tables. */
define( 'DB_CHARSET', getenv_docker('WORDPRESS_DB_CHARSET', 'utf8') );

/** The database collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', getenv_docker('WORDPRESS_DB_COLLATE', '') );

/**#@+
 * Authentication unique keys and salts.
 *
 * Change these to different unique phrases! You can generate these using
 * the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}.
 *
 * You can change these at any point in time to invalidate all existing cookies.
 * This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define( 'AUTH_KEY',         getenv_docker('WORDPRESS_AUTH_KEY',         '203f0a21a2d069a786c00bc0ba433bf77eaac229') );
define( 'SECURE_AUTH_KEY',  getenv_docker('WORDPRESS_SECURE_AUTH_KEY',  'be09d4bcdf946736f423c3c187aae16495fcc98e') );
define( 'LOGGED_IN_KEY',    getenv_docker('WORDPRESS_LOGGED_IN_KEY',    '057433ae2aff554083efaa924a01281cf367ca31') );
define( 'NONCE_KEY',        getenv_docker('WORDPRESS_NONCE_KEY',        '1b77dfe810ade10f6840ab5212e4a9eab3feacf5') );
define( 'AUTH_SALT',        getenv_docker('WORDPRESS_AUTH_SALT',        '5b0cfe1954e3636ebabdb3cd728523574c9b278d') );
define( 'SECURE_AUTH_SALT', getenv_docker('WORDPRESS_SECURE_AUTH_SALT', '1774ab01e1a978d343b7928ab16ef4be8d2624ef') );
define( 'LOGGED_IN_SALT',   getenv_docker('WORDPRESS_LOGGED_IN_SALT',   '17d43b0ceb9e6bef5fd89d21e93c664e659350b7') );
define( 'NONCE_SALT',       getenv_docker('WORDPRESS_NONCE_SALT',       '70c36475c27efe1f1f5fcd92c005b929ca99935c') );
// (See also https://wordpress.stackexchange.com/a/152905/199287)

/**#@-*/

/**
 * WordPress database table prefix.
 *
 * You can have multiple installations in one database if you give each
 * a unique prefix. Only numbers, letters, and underscores please!
 */
$table_prefix = getenv_docker('WORDPRESS_TABLE_PREFIX', 'wp_');

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 *
 * For information on other constants that can be used for debugging,
 * visit the documentation.
 *
 * @link https://wordpress.org/support/article/debugging-in-wordpress/
 */
define( 'WP_DEBUG', true );

/* Add any custom values between this line and the "stop editing" line. */

// If we're behind a proxy server and using HTTPS, we need to alert WordPress of that fact
// see also https://wordpress.org/support/article/administration-over-ssl/#using-a-reverse-proxy
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) {
	$_SERVER['HTTPS'] = 'on';
}
// (we include this by default because reverse proxying is extremely common in container environments)

if ($configExtra = getenv_docker('WORDPRESS_CONFIG_EXTRA', '')) {
	eval($configExtra);
}

/* That's all, stop editing! Happy publishing. */

/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
	define( 'ABSPATH', __DIR__ . '/' );
}

/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';
EOF

docker compose up -d
echo "WordPressのセットアップが完了しました。 http://localhost でアクセスしてください!"
echo "phpMyAdminは http://localhost:8888 で利用できます。"

使い方

  1. スクリプトを `wp-new` として保存
  2. /usr/local/bin/(グローバルに使う場合)
  3. 実行権限を付与
    sudo chmod +x wp-new
  4. 新しいWordPressプロジェクトを作成
    sudo wp-new my-wordpress

動作確認

  • MySQLのログイン情報
    • ユーザー名: root または wordpress
    • パスワード: root または wordpress

これで、Laravelの laravel new のように `wp-new` で新しいWordPress環境を素早く構築できます。

WordPressをViteで開発する

(1) WordPress テーマディレクトリの準備

まず、WordPress のテーマディレクトリを作成します(例: my-theme)。

cd my-wordpress/wp-content/themes
mkdir my-theme && cd my-theme

(2) package.json を作成

テーマディレクトリ(my-theme/)内で Vite をセットアップ:

npm init -y
npm install vite --save-dev

開発用の依存パッケージをインストール

npm install sass postcss autoprefixer sass-embedded --save-dev

(3) Vite の設定ファイル vite.config.mjs を作成

my-theme/vite.config.mjs を作成し、WordPress のエントリーポイントとして main.js を指定します。

import { defineConfig } from 'vite';

export default defineConfig({
  root: 'src',
  build: {
    emptyOutDir: true,
    rollupOptions: {
      input: {
        main: './src/main.js'
      },
      output: {
        entryFileNames: 'main.js', // JSはmain.jsで出力
        assetFileNames: (assetInfo) => {
          if (assetInfo.name && assetInfo.name.endsWith('.css')) {
            return 'style.css'; // SCSSは style.css として出力
          }
          return '[name].[ext]';
        }
      }
    }
  }
});

(4) src/ ディレクトリを作成

Vite の開発用ファイルを src/ フォルダに配置。

mkdir src
touch src/main.js
mkdir src/css
touch src/css/style.scss

src/main.js(エントリーポイント)

import './css/style.scss';

console.log('Vite is running with WordPress!');

src/css/style.scss(SCSS スタイル)

body {
  background-color: #f8f8f8;
}

2. WordPress のテーマと連携

(1) functions.php に Vite の HMR を組み込む

my-theme/functions.php に以下のコードを追加し、Vite のバンドルされたファイルをロードします。

<?php

function mytheme_enqueue_scripts() {
    if (defined('WP_DEBUG') && WP_DEBUG) {
        // JS (type="module"が必要なので直接書く)
        add_action('wp_print_scripts', function () {
            echo '<script type="module" src="http://localhost:5173/main.js"></script>';
        });
    } else {
        wp_enqueue_style('mytheme-style', get_template_directory_uri() . '/src/dist/style.css');
        add_action('wp_print_scripts', function () {
            $directory = get_template_directory_uri();
            echo '<script type="module" src="' . $directory . '/src/dist/main.js"></script>';
        });
    }
}
add_action('wp_enqueue_scripts', 'mytheme_enqueue_scripts');

(2) テーマの style.css を作成

my-theme/style.css を作成し、WordPress に認識させる。

/*
Theme Name: My WordPress Theme with Vite
Author: Your Name
Version: 1.0
*/

3. Vite の開発・ビルド

(1) Vite の開発サーバーを起動

以下のコマンドを実行すると、WordPress と Vite の HMR(ホットリロード)が動作します。

npm run dev

Missing script: “dev”とエラーが出る場合

下記記述をpacage.jsonに追記してください。

{
  "name": "theme_2025",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "vite", #👈ここ
    "build": "vite build" #👈ここ
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "devDependencies": {
    "autoprefixer": "^10.4.20",
    "postcss": "^8.5.3",
    "sass": "^1.85.1",
    "vite": "^6.2.1"
  }
}

(2) ビルド(本番用)

本番環境で WordPress に適用するには、以下を実行:

npm run build

これにより、src/dist/assets フォルダにバンドルされたファイルが出力され、WordPress で利用可能になります。


WordPressをGitで管理する

WordPressのプロジェクトをGitで管理する際には、テーマディレクトリ(例: wp-content/themes/mytheme/)で git init を実行し、そのディレクトリ単位でバージョン管理を行う。これにより、WordPressのコアファイルや不要なアップロードデータを含めず、テーマの開発に集中できる。

まとめ

  • WordPressをDockerで環境構築し、簡単にセットアップできるスクリプトを作成
  • Viteを導入し、WordPressのテーマ開発を効率化
  • .gitignore を適切に設定し、Gitで管理しやすい構成に

この方法を活用すれば、Laravelの開発環境に近い形でWordPressを管理・開発できるようになります。特に、Viteの導入により、ホットリロードによる素早いフィードバックが可能になり、開発速度が向上する。また、モジュールバンドラーとしてのViteの特性を活かすことで、コードの保守性も向上し、長期的な運用がしやすくなるかと思います。

2025/05/08追記

久々に自分の記事を見て構築すると、余計な部分や不可解な点があったので、修正しました。 また、よくよく考えてみたらthemesディレクトリに置いているpackage.jsonなどのファイル全て公開されてしまいますね。 使用する際は大事な情報を配置しないよう気をつけてください。 どなたか隠すためのいい方法があれば教えてください🙇

Rebellion Logo