WordPressテーマにReactを統合

目次

参考サイト

Reactを使用してWordPressテーマを開発する方法
https://kinsta.com/jp/blog/wordpress-react-theme/

前提条件

  • WordPressサイト(ローカル開発環境推奨)
  • Node.jsとnpm(またはyarn)のインストール
ステップ1: 開発環境セットアップ 1 開発環境でのみNode.jsが必要 React + @wordpress/scriptsを使用してコンポーネントを開発 Node.js 開発環境 ビルドツール npm/yarn React コンポーネント JSX開発 UI作成 @wordpress/ scripts ビルド設定 済みパッケージ ⚠️ 重要 この段階でのみNode.jsが必要です npm install @wordpress/scripts @wordpress/element npm start

1. WordPressテーマの基本構造を作成

  1. wp-content/themesディレクトリに新しいフォルダを作成(例:my-react-theme
  2. 以下のファイルを作成:
    • style.css:テーマ情報を含むメインスタイルシート
    • functions.php:テーマ機能を定義
    • index.php:メインテンプレートファイル
  3. style.cssにテーマ情報を追加:
/*
Theme Name: My React Theme
Author: Your Name
Description: A WordPress theme with React integration
Version: 1.0
*/
ステップ2: Reactコンポーネント作成 2 WordPressテーマファイル + React作成 通常のWordPressテーマ構造にReactを統合 📁 my-react-theme/ WordPress必須ファイル 📄 style.css 📄 functions.php 📄 index.php 📄 package.json Reactコンポーネント 📁 src/ ├── App.js ├── Header.js └── Posts.js functions.phpでReactファイルを読み込み設定 index.phpに <div id=”app”></div> を配置 wp_enqueue_script(‘my-react-app’, ‘build/index.js’) render(<App />, document.getElementById(‘app’))
ステップ3: ビルド処理 3 npm run build で静的ファイル生成 Reactコードをブラウザで動作するJSに変換 ビルド前 📄 App.js (JSX) 📄 Header.js (JSX) 📄 Posts.js (JSX) 📄 style.scss 📄 ES6+ コード ブラウザで直接動作不可 npm run build @wordpress/scripts ビルド後 📁 build/ ├── index.js ├── index.css └── 圧縮済み ブラウザで動作可能 静的ファイル 🔑 重要: この段階で静的ファイルが完成 以降はNode.js不要でWordPressサーバーにデプロイ可能
ステップ4: 静的ファイル完成 4 デプロイ準備完了 ブラウザで動作する静的ファイルが生成されました 📁 完成したテーマフォルダ WordPressファイル 📄 style.css 📄 functions.php 📄 index.php 📄 package.json 📁 src/ (開発用) 静的ファイル 📁 build/ ├── index.js ⭐ ├── index.css ⭐ └── chunk files デプロイ用ファイル ✅ 特徴 • 圧縮済み • 最適化済み • ブラウザ互換 • 本番対応 🚫 Node.js不要 以降はWordPressサーバーのみで動作
ステップ5: 本番環境デプロイ 5 WordPressサーバーにデプロイ Node.js不要!通常のWordPress環境で動作 WordPressサーバー PHP 8.0+ MySQL/MariaDB Apache/Nginx WordPress Core ✅ 通常のWordPress環境 ❌ Node.js不要 動作の流れ 1. ユーザーアクセス PHP 2. PHPでHTML生成 JS 3. 静的JSファイル読み込み React 4. ブラウザでReact実行 🎉 完成! • 通常のWordPress環境 • Reactの動的UI • Node.js不要

2. ReactをWordPressに統合

  1. テーマディレクトリで以下のコマンドを実行:
npm init -y
npm install @wordpress/scripts @wordpress/element --save-dev
  1. package.jsonに以下のスクリプトを追加:
"scripts": {
  "start": "wp-scripts start",
  "build": "wp-scripts build"
}
  1. srcディレクトリを作成し、index.jsApp.jsファイルを追加
  2. functions.phpにスクリプトエンキュー関数を追加:
function enqueue_react_scripts() {
    wp_enqueue_script('my-react-theme', get_template_directory_uri() . '/build/index.js', ['wp-element'], '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'enqueue_react_scripts');
  1. index.phpを更新してReactアプリケーションのマウントポイントを追加:
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
    <div id="root"></div>
    <?php wp_footer(); ?>
</body>
</html>

3. Reactコンポーネントの開発

  1. src/App.jsにメインコンポーネントを作成:
import { Component } from '@wordpress/element';

class App extends Component {
    render() {
        return <h1>Hello, WordPress and React!</h1>;
    }
}

export default App;
  1. src/index.jsでアプリケーションをレンダリング:
import { render } from '@wordpress/element';
import App from './App';

render(<App />, document.getElementById('root'));

4. WordPressデータの統合

WordPress REST APIを使用してWordPressのデータをReactコンポーネントに統合できます:

  1. src/Posts.jsコンポーネントを作成:
import { Component } from '@wordpress/element';

class Posts extends Component {
    state = { posts: [] };

    componentDidMount() {
        fetch('/wp-json/wp/v2/posts')
            .then(response => response.json())
            .then(posts => this.setState({ posts }));
    }

    render() {
        return (
            <div>
                {this.state.posts.map(post => (
                    <h2 key={post.id}>{post.title.rendered}</h2>
                ))}
            </div>
        );
    }
}

export default Posts;
  1. App.jsでPostsコンポーネントを使用

5. テーマのビルドと有効化

  1. 開発モードで実行:npm start
  2. 本番用ビルド:npm run build
  3. WordPress管理画面でテーマを有効化

この記事を書いた人

目次