>此CSS-Tricks教程構建了有關WordPress塊的先前帖子,重點是從前端的外部API獲取和顯示動態內容。 雖然較早的教程涵蓋了基礎知識和後端渲染,但該教程探討了在自定義塊中使用外部數據。
這是涵蓋將外部API數據集成到自定義WordPress塊的各個方面的系列的一部分:
@wordpress/create-block
設置塊插件
目錄中並激活它之後,我們將重點放在這些關鍵文件上:
>npx @wordpress/create-block football-rankings
wp-content/plugins
edit.js
index.js
football-rankings.php
中獲取數據
>edit.js
useEffect
> WordPress中的數據存儲edit.js
import { useEffect } from "@wordpress/element"; export default function Edit(props) { // ... (rest of the code remains largely unchanged) useEffect(() => { // ... (fetch code using RapidAPI key and host) .then( ( response ) => response.json() ) .then( ( response ) => { setAttributes( { data: response } ); //Simplified data assignment }) .catch((err) => console.error(err)); }, []); // ... (rest of the code remains largely unchanged) }
index.js
這確保WordPress將API數據保存在數據庫中。
data
前端輸出
registerBlockType( metadata.name, { // ... attributes: { data: { type: "object", }, }, // ... } );
和
(或)中時,使用frontend.js
>和frontend.css
來招募這些資產。 frontend.scss
>中的football-rankings.php
函數將屬性傳遞給前端JavaScript。 wp_enqueue_script
wp_enqueue_style
!is_admin()
render_callback
football-rankings.php
文件(簡化):
npx @wordpress/create-block football-rankings
> frontend.scss
或frontend.css
中的樣式負責數據的可視化表示。 package.json
文件的scripts
部分應更新以在構建過程中包含前端文件。
以上是在前端的WordPress塊中渲染外部API數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!