如何使用 React 構(gòu)建 WordPress 主題

創(chuàng)建基本的 WordPress 主題結(jié)構(gòu)

創(chuàng)建基本的 WordPress 主題結(jié)構(gòu)包括設(shè)置一系列文件和目錄,WordPress 使用這些文件和目錄將主題的樣式、功能和布局應(yīng)用到 WordPress 網(wǎng)站。

1.在你的網(wǎng)站運(yùn)行環(huán)境中,訪問站點(diǎn)的文件夾。導(dǎo)航到wp-content/themes 目錄。

2.給主題創(chuàng)建一個(gè)新文件夾。文件夾名稱應(yīng)該是唯一的且具有描述性——例如my-basic-theme。

3.在主題的文件夾中,創(chuàng)建這些基本文件并將其留空:

圖片[1]-如何使用 React 構(gòu)建 WordPress 主題-光子波動網(wǎng) | 專業(yè)WordPress修復(fù)服務(wù),全球范圍,快速響應(yīng)

如果不使用 React,還必須創(chuàng)建下面這些文件。

  • header.php  — 包含站點(diǎn)的標(biāo)頭部分。
  • footer.php  — 包含網(wǎng)站的頁腳部分。
  • sidebar.php  — 對于側(cè)邊欄部分,如果主題包含側(cè)邊欄。

接下來,打開style.css 并將以下內(nèi)容添加到文件頂部:

/*
Theme Name: My Basic Theme
Theme URI: http://example.com/my-basic-theme/
Author: Your Name
Author URI: http://example.com
Description: A basic WordPress theme.
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: blog, custom-background
Text Domain: my-basic-theme
*/

這個(gè)代碼片段是 WordPress 主題 style.css 文件的標(biāo)題部分,包含主題名稱、作者詳細(xì)信息、版本和許可證等重要元數(shù)據(jù)。它有助于 WordPress 在儀表板中識別和顯示主題,包括主題描述和分類標(biāo)簽。

將 React 整合到 WordPress 中

將 React 整合到 WordPress 主題中,就可以使用 React 基于組件的架構(gòu),在 WordPress 網(wǎng)站中構(gòu)建動態(tài)的交互式用戶界面。要集成 React,將會使用@wordpress/scripts 包。

這是一個(gè)專為 WordPress 開發(fā)定制的可重用腳本集合。WordPress 提供它是為了簡化配置和構(gòu)建過程,尤其是在 WordPress 主題和插件中集成 React 等現(xiàn)代 JavaScript 工作流時(shí)。工具包封裝了常用任務(wù),使在 WordPress 生態(tài)系統(tǒng)中使用 JavaScript 進(jìn)行開發(fā)變得更加容易。

圖片[2]-如何使用 React 構(gòu)建 WordPress 主題-光子波動網(wǎng) | 專業(yè)WordPress修復(fù)服務(wù),全球范圍,快速響應(yīng)

調(diào)整你的主題

現(xiàn)在已經(jīng)掌握了 WordPress 主題的基本結(jié)構(gòu),可以對主題進(jìn)行調(diào)整。

1.在主題目錄下,將以下代碼粘貼到 functions.php 文件中:

<?php
function my_react_theme_scripts() {
    wp_enqueue_script('my-react-theme-app', get_template_directory_uri() . '/build/index.js', array('wp-element'), '1.0.0', true);
    wp_enqueue_style('my-react-theme-style', get_stylesheet_uri());
}

add_action('wp_enqueue_scripts', 'my_react_theme_scripts');

function.php文件 將 React 與你的 WordPress 主題整合。它使用wp_enqueue_script 和wp_enqueue_style 功能將 JavaScript 和級聯(lián)樣式表 ( CSS ) 文件添加到您的主題。

WordPresswp_enqueue_script 函數(shù)有幾個(gè)參數(shù):

  • 句柄名稱 ( 'my-react-theme-app'),唯一標(biāo)識腳本
  • 腳本文件的路徑
  • 依賴項(xiàng)數(shù)組array('wp-element'),表示腳本依賴于 WordPress 的 React 包裝器('wp-element')。
  • 版本號('1.0.0')
  • 位置true,指定腳本應(yīng)加載到 HTML 文檔的頁腳中以提高頁面加載性能

wp_enqueue_style 函數(shù)采用以下參數(shù):

  • 句柄名稱'my-react-theme-style',唯一標(biāo)識樣式表
  • source ,返回主題主樣式表 ( style.cssget_stylesheet_uri() )的 URL并確保應(yīng)用主題的樣式
  • add_action 元素,將自定義函數(shù)掛鉤  'my_react_theme_scripts' 到特定操作 ( 'wp_enqueue_scripts')。這可以確保當(dāng) WordPress 準(zhǔn)備渲染頁面時(shí)正確加載 JavaScript 和 CSS。
圖片[3]-如何使用 React 構(gòu)建 WordPress 主題-光子波動網(wǎng) | 專業(yè)WordPress修復(fù)服務(wù),全球范圍,快速響應(yīng)

這段代碼可確保 React 應(yīng)用程序的已編譯 JavaScript 文件(位于 /build/index.js 中)和主題的主樣式表與主題一起加載。

/build 目錄通常 來自使用webpackcreate-react-app 等工具編譯 React 應(yīng)用程序,這些工具會將 React 代碼捆綁成可用于生產(chǎn)的、經(jīng)過精簡的 JavaScript 文件。

這種設(shè)置對于將 React 功能集成到 WordPress 主題中至關(guān)重要,可以在 WordPress 網(wǎng)站中實(shí)現(xiàn)動態(tài)的、類似應(yīng)用程序的用戶體驗(yàn)。

2.接下來,更新index.php文件的內(nèi)容 :

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
    <div id="app"></div>
    <?php wp_footer(); ?>
</body>
</html>

index.php 文件中的代碼定義了 WordPress 主題的基本 HTML 結(jié)構(gòu),包括供 WordPress 插入必要頁眉(wp_head)和頁腳(wp_footer)的鉤子,以及一個(gè)帶有 ID app 的 div,其中安裝了 React 應(yīng)用程序。

使用 @wordpress/scripts 設(shè)置 React

1.打開終端并導(dǎo)航到主題的目錄:cd wp-content/themes/my-basic

cd wp-content/themes/my-basic-theme

2.初始化一個(gè)新的 Node.js 項(xiàng)目:

npm init -y

3.安裝@wordpress/scripts@wordpress/element

npm install @wordpress/scripts @wordpress/element --save-dev

注意:這里通常需要幾分鐘的時(shí)間,耐心等待就好。

4.修改package.json 文件以包含start 一個(gè)build 腳本:

"scripts": {
  "start": "wp-scripts start",
  "build": "wp-scripts build"
},

@wordpress/scripts “用于以熱重載方式啟動開發(fā)服務(wù)器以進(jìn)行開發(fā)(啟動),并將 React 應(yīng)用程序編譯成靜態(tài)資產(chǎn)以用于生產(chǎn)(構(gòu)建)。

圖片[4]-如何使用 React 構(gòu)建 WordPress 主題-光子波動網(wǎng) | 專業(yè)WordPress修復(fù)服務(wù),全球范圍,快速響應(yīng)

創(chuàng)建一個(gè)反應(yīng)項(xiàng)目

1. 為主題中的 React 源文件創(chuàng)建一個(gè)名為src的新目錄。

2.在src 文件夾中,創(chuàng)建兩個(gè)新文件:index.js 和App.js。

3.將以下代碼放入index.js

import { render } from '@wordpress/element';
import App from './App';
render(, document.getElementById('app'))

上面的代碼render 從@wordpress/element 組件導(dǎo)入函數(shù)App 。然后,它將App 組件安裝到文檔對象模型 (DOM)。

4.接下來,將此代碼粘貼到App.js 文件中:

import { Component } from '@wordpress/element';
export default class App extends Component {
  render() {
    return (
      <div> 
        <h1>Hello, WordPress and React!</h1>
        {/* Your React components will go here */}
      </div>
);
    }
}

完成并激活主題

激活主題:

  1. 使用npm start運(yùn)行開發(fā)服務(wù)器。
  2. 在 WordPress 控制面板中找到 “外觀”>”主題”,找到你的主題并點(diǎn)擊 “激活”,激活你的新主題。
  3. 確保 React 項(xiàng)目的構(gòu)建過程配置正確,以輸出到正確的主題目錄,從而允許 WordPress 渲染 React 組件。
  4. 訪問 WordPress 網(wǎng)站的前端,查看實(shí)時(shí)更改。
圖片[5]-如何使用 React 構(gòu)建 WordPress 主題-光子波動網(wǎng) | 專業(yè)WordPress修復(fù)服務(wù),全球范圍,快速響應(yīng)

為主題開發(fā)React組件

接下來,采用基于組件的方法,在 WordPress 主題中使用特定組件(如標(biāo)題)擴(kuò)展基本的 React 設(shè)置。

創(chuàng)建標(biāo)題組件

在主題的 src 目錄中,為標(biāo)題組件創(chuàng)建一個(gè)新文件。為文件命名,如 Header.js,并添加以下代碼:

import { Component } from '@wordpress/element';
class Header extends Component {
    render() {
        const { toggleTheme, darkTheme } = this.props;
        const headerStyle = {
            backgroundColor: darkTheme ? '#333' : '#EEE',
            color: darkTheme ? 'white' : '#333',
            padding: '10px 20px',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
        };
        return (
            <header style={headerStyle}>
                <div>My WP Theme</div>
                <button onClick={toggleTheme}>{darkTheme ? 'Light Mode' : 'Dark Mode'}</button>
            </header>
        );
    }
}
export default Header;

這段代碼使用”@wordpress/element “定義了一個(gè)標(biāo)題組件,可根據(jù) darkTheme 命題動態(tài)調(diào)整標(biāo)題樣式。它包含一個(gè)按鈕,可通過調(diào)用作為道具傳遞的 toggleTheme 方法在淺色和深色主題之間切換。

在主題的 src 目錄中,為頁腳組件創(chuàng)建一個(gè)新文件。給它起個(gè)名字,例如 Footer.js,然后添加以下代碼:

import { Component } from '@wordpress/element';
class Footer extends Component {
    render() {
        const { darkTheme } = this.props;
        const footerStyle = {
            backgroundColor: darkTheme ? '#333' : '#EEE',
            color: darkTheme ? 'white' : '#333',
            padding: '20px',
            textAlign: 'center',
        };
        return (
            <footer> style={footerStyle}>
                ? {new Date().getFullYear()} My WP Theme
            </footer>
        );
    }
}
export default Footer;

這段代碼定義了一個(gè)頁腳組件,它根據(jù) darkTheme 命題渲染具有動態(tài)樣式的頁腳,并顯示當(dāng)前年份。

更新App.js文件

要使用新的頁眉和頁腳,用以下代碼替換 App.js 文件的內(nèi)容:

import { Component } from '@wordpress/element';
import Header from './Header';
import Footer from './Footer';
export default class App extends Component {
    state = {
        darkTheme: true,
    };
    toggleTheme = () => {
        this.setState(prevState => ({
            darkTheme: !prevState.darkTheme,
        }));
    };
    render() {
        const { darkTheme } = this.state;
        return (
            <div>
                <Header darkTheme={darkTheme} toggleTheme={this.toggleTheme} />
                <main style={{ padding: '20px', background: darkTheme ? '#282c34' : '#f5f5f5', color: darkTheme ? 'white' : 'black' }}>               
                </main>
                <Footer darkTheme={darkTheme} />
            </div>
        );
    }
}

開發(fā)構(gòu)建過程會監(jiān)控更改并重新編譯代碼,該過程應(yīng)仍處于激活狀態(tài)。最后一個(gè)模板版本應(yīng)該與這個(gè)相似:

圖片[6]-如何使用 React 構(gòu)建 WordPress 主題-光子波動網(wǎng) | 專業(yè)WordPress修復(fù)服務(wù),全球范圍,快速響應(yīng)

如何在 React 中處理 WordPress 數(shù)據(jù)

將 WordPress 內(nèi)容集成到 React 應(yīng)用程序中,在 WordPress 強(qiáng)大的內(nèi)容管理 功能和 React 的動態(tài) UI 設(shè)計(jì)之間建立了無縫橋梁。這可以通過 WordPress REST API 實(shí)現(xiàn)。

要訪問WordPress REST API,請通過更新永久鏈接設(shè)置來啟用它。在 WordPress 管理儀表盤上,導(dǎo)航至“設(shè)置”  > “永久鏈接”。選擇“帖子名稱”選項(xiàng)或“普通” 以外的任何選項(xiàng) ,然后保存更改。

在主題的src目錄中,創(chuàng)建一個(gè)名為Posts.js 的 新文件 并添加下面代碼:

import { Component } from '@wordpress/element';
class Posts extends Component {
    state = {
        posts: [],
        isLoading: true,
        error: null,
    };
    componentDidMount() {
        fetch('http://127.0.0.1/wordpress_oop/wp-json/wp/v2/posts')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Something went wrong');
                }
                return response.json();
            })
            .then(posts => this.setState({ posts, isLoading: false }))
            .catch(error => this.setState({ error, isLoading: false }));
    }
    render() {
        const { posts, isLoading, error } = this.state;
        if (error) {
            return <div>Error: {error.message}</div>;
        }
        if (isLoading) {
            return <div>Loading...</div>;
        }
        return (
            <div>
                {posts.map(post => (
                    <article key={post.id}>
                        <h2 dangerouslySetInnerHTML={{ __html: post.title.rendered }} />
                        <div dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }} />
                    </article>
                ))}
            </div>
        );
    }
}
export default Posts;

根據(jù) WP 部署名稱(即你安裝 WP 的文件夾)的不同,fetch(‘http://127.0.0.1/wordpress_oop/wp-json/wp/v2/posts’) URL 可能略有不同。或者,也可以從 DevKinsta 面板獲取網(wǎng)站主機(jī)名,然后添加后綴 /wp-json/wp/v2/posts。

帖子組件是這種集成的一個(gè)典型例子,它演示了使用 WordPress REST API 獲取和管理 WordPress 數(shù)據(jù)(特別是帖子)的過程。

通過在組件的生命周期方法(componentDidMount)中發(fā)起網(wǎng)絡(luò)請求,該組件可以高效地從 WordPress 網(wǎng)站獲取帖子并將其存儲在自己的狀態(tài)中。這種方法強(qiáng)調(diào)了一種將 WordPress 數(shù)據(jù)(如頁面或自定義帖子類型)動態(tài)整合到 React 組件中的模式。要使用新組件,用以下代碼替換 App.js 文件的內(nèi)容:

import { Component } from '@wordpress/element';
import Header from './Header';
import Footer from './Footer';
import Posts from './Posts'; // Import the Posts component

export default class App extends Component {
    state = {
        darkTheme: true,
    };
    toggleTheme = () => {
        this.setState(prevState => ({
            darkTheme: !prevState.darkTheme,
        }));
    };
    render() {
        const { darkTheme } = this.state;
        return (
            <div>
                <Header darkTheme={darkTheme} toggleTheme={this.toggleTheme} />
                <main style={{ padding: '20px', background: darkTheme ? '#282c34' : '#f5f5f5', color: darkTheme ? 'white' : 'black' }}>
                    <Posts /> {/* Render the Posts component */}
                </main>

                <Footer darkTheme={darkTheme} />
            </div>
        );
    }
}

現(xiàn)在可以查看主題的最新最終版本。除了頁眉和頁腳,它還包括一個(gè)動態(tài)內(nèi)容區(qū)域,用于展示帖子。

圖片[7]-如何使用 React 構(gòu)建 WordPress 主題-光子波動網(wǎng) | 專業(yè)WordPress修復(fù)服務(wù),全球范圍,快速響應(yīng)

在 WordPress 項(xiàng)目中使用 React WordPress 主題

要將基于 React 的主題集成到 WordPress 項(xiàng)目中,首先要利用 @wordpress/scripts 等軟件包將 React 代碼轉(zhuǎn)換為 WordPress 兼容的格式。該工具簡化了構(gòu)建過程,讓你可以將 React 應(yīng)用程序編譯成 WordPress 可以啟動的靜態(tài)資產(chǎn)。

使用 @wordpress/scripts 提供的 npm 命令,構(gòu)建主題非常簡單。在主題目錄下運(yùn)行 npm run build,即可將 React 代碼編譯成靜態(tài) JavaScript 和 CSS 文件。

然后,將這些編譯好的資產(chǎn)放入主題中的相應(yīng)目錄,確保 WordPress 可以正確加載和呈現(xiàn) React 組件作為主題的一部分。集成完成后,就可以像激活其他主題一樣激活 React WordPress 主題,立即為 WordPress 網(wǎng)站帶來類似應(yīng)用程序的現(xiàn)代用戶體驗(yàn)。

總結(jié)

通過使用 React 強(qiáng)大的 UI 功能構(gòu)建主題并將其集成到 WordPress 中,可以釋放創(chuàng)建靈活、高度交互且以用戶為中心的 Web 體驗(yàn)。


聯(lián)系我們
教程看不懂?聯(lián)系我們?yōu)槟赓M(fèi)解答!免費(fèi)助力個(gè)人,小企站點(diǎn)!
客服微信
客服微信
電話:020-2206-9892
QQ咨詢:1025174874
郵件:info@361sale.com
工作時(shí)間:周一至周五,9:30-18:30,節(jié)假日休息
? 轉(zhuǎn)載聲明
本文作者:Harry
THE END
喜歡就支持一下吧
點(diǎn)贊0 分享
評論 搶沙發(fā)

請登錄后發(fā)表評論

    暫無評論內(nèi)容