>此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中文网其他相关文章!