解鎖Gutenberg潛能:用樣式變體與區塊變體打造動畫寶麗來圖片

解鎖Gutenberg潛能:用樣式變體與區塊變體打造動畫寶麗來圖片

文章目录

  • 區塊樣式與區塊變體
  • 核心影像區塊上的動畫寶麗來效果
  • 環境設定
  • 註冊區塊樣式
  • 構建邏輯
  • 註冊區塊變體
  • 測試和除錯
  • 小結

解鎖Gutenberg潛能:用樣式變體與區塊變體打造動畫寶麗來圖片

Gutenberg 已發展成為一款功能強大且高度可定製的編輯器。除了其強大的開箱即用功能外,WordPress 開發者現在還可以利用豐富的 API 輕鬆地將自定義功能整合到他們的網站中。這種可擴充套件性實現了高度定製化的開發,使開發者能夠打造高度個性化且功能豐富的線上體驗。

本文探討了兩個鮮為人知但功能強大的 WordPress 開發功能:樣式變體(也稱為區塊樣式)和區塊變體。

雖然它們的實用性乍一看可能有些晦澀難懂,但您會驚訝於它們的實用性,並且只需投入少量時間就能將它們無縫整合到您的工作流程中。

您將透過一個實際專案親身體驗它們的含義以及如何使用它們。您只需複製貼上本教程中的程式碼,並最終新增自定義設定,即可在您的 WordPress 網站上實現此專案。

在深入研究專案之前,我們先快速回顧一下先決條件:

  • 本地 WordPress 開發環境:任何環境都可以,但我們強烈推薦本地開發套件 DevKinsta。它易於使用,並提供許多設定和工具,可快速啟動和管理本地 WordPress 網站。
  • Node.js 和 npm:這些至關重要,因為區塊編輯器基於 React 構建,需要構建過程。
  • 基本的前端開發技能:對 Node.js、JavaScript(基於 React)、PHP 和 CSS 有基本的瞭解將大有裨益。

雖然這個專案並不複雜,但請做好編寫一些程式碼的準備。完整的程式碼也可在 GitHub 上找到。

區塊樣式與區塊變體

區塊樣式區塊變體是 WordPress 中兩個強大的開發者功能。雖然它們的名稱聽起來很相似,但在用途和用法上卻有所不同。

區塊樣式(也稱為樣式變體)是預先構建的 CSS 樣式集,允許您透過單擊更改區塊的外觀。註冊區塊樣式後,塊側邊欄中會出現一個按鈕,用於為該區塊分配一組預先構建的樣式。您可以開啟或關閉樣式,並在編輯器中即時預覽區塊。

核心影像區<mark class=

核心影像區塊有兩種預設樣式變體。

樣式變體不會改變區塊的屬性。它們僅透過為區塊的封裝元素分配 CSS 類來修改區塊的外觀。

區塊變體是一個更強大的工具,因為它們允許您建立包含屬性和內部區塊的預配置區塊版本。它們還會顯示在編輯器的區塊插入器中。本質上,區塊變體在使用者看來就像一個獨立的區塊,完全獨立於構建它的區塊。

區塊變體允許自定義區塊的外觀、初始設定和結構。

考慮到所有這些,讓我們利用這些工具將 Gutenberg 區塊提升到一個新的水平!

核心影像區塊上的動畫寶麗來效果

現在,讓我們深入研究我們的專案!我們將使用 Gutenberg 外掛擴充套件核心圖片區塊,以實現以下功能:

  • 實現寶麗來風格變體:使用者只需在區塊的設定側邊欄中單擊一下,即可為圖片新增迷人的寶麗來效果。
  • 新增懸停動畫:我們將使用精妙的懸停動畫來增強寶麗來風格圖片的效果。
  • 建立“動畫寶麗來”區塊變體:這將允許使用者直接從區塊插入器快速插入帶有懸停效果的預配置寶麗來圖片。

準備好了嗎?讓我們開始設定外掛!

影像區<mark class=

影像區塊上的動畫效果

環境設定

開始之前,我們需要使用 Node.js 搭建一個 WordPress 開發環境。我們假設您已經安裝了本地 WordPress 開發環境以及最新版本的 Node.jsnpm。如果您需要幫助,請檢視我們的教程,瞭解如何構建 Gutenberg 外掛以向區塊編輯器新增功能

步驟 1 – 建立基本外掛結構

在本教程中,我們將外掛命名為 Image Hacker

導航到您的 plugins 目錄並建立一個新的 image-hacker 資料夾。在此資料夾中,建立一個新的 image-hacker.php 檔案(外掛的主檔案)和一個 src 子資料夾,您將在其中構建外掛的功能。

以下是您的外掛的基本結構:

/wp-content/plugins/
└── /image-hacker/
├── image-hacker.php
└── /src/

步驟 2 – 建立PHP程式碼

接下來,您需要確保 WordPress 能夠識別您的外掛。為此,請將以下程式碼新增到 image-hacker.php

<?php
/**
* Plugin Name: Image Hacker
* Description: Adds new features to the core Image block
* Version:     1.0.0
* Author:      Your Name
* License:     GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: image-hacker
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}

步驟 3 – 初始化npm並安裝依賴項

開啟您常用的命令列工具,並導航到外掛目錄。到達那裡後,執行以下命令:

npm init -y

此命令會初始化一個新的 package.json 檔案,其中包含專案的依賴項和指令碼。

接下來,您需要安裝 WordPress 指令碼以及 webpack 和 Babel 等構建工具:

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

此命令新增一個包含節點依賴項的 node_modules 資料夾和一個 package-lock.json 檔案。下圖顯示了 Visual Studio Code 中專案的當前結構:

Visual Studio Code 中的 Gutenberg 外掛

Visual Studio Code 中的 Gutenberg 外掛

接下來,開啟 package.json 檔案並更新 scripts 屬性,如下所示:

{
"name": "image-hacker",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"build": "wp-scripts build",
"start": "wp-scripts start"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"@wordpress/plugins": "^7.25.0",
"@wordpress/scripts": "^30.18.0"
}
}

請注意,devDependencies 版本可能與上述版本不同,具體取決於您環境中實際安裝的版本。

步驟 4 – 建立外掛原始檔

下一步是建立外掛原始檔。導航到 src 資料夾並新增以下檔案:

  • index.js
  • style.scss
  • editor.scss

外掛結構現在應該如下所示:

/wp-content/plugins/
└── /image-hacker/
├── /node-modules/
├── image-hacker.php
├── package.json
├── package-lock.json
└── /src/
├── index.js
├── style.scss
└── editor.scss

現在開啟您的 WordPress 管理面板並導航到外掛螢幕。找到 Image Hacker 外掛並啟用它。

注:editor.scss 檔案僅用於宣告編輯器的區塊樣式,而 style.scss 檔案則包含編輯器和前端的區塊樣式。在本專案中,我們不會使用 editor.scss 檔案。

步驟 5 – 在外掛檔案中引入資源

接下來,您需要在主外掛檔案中引入外掛資源。在 image-hacker.php 檔案中新增以下內容:

/**
* Enqueue block editor assets.
*/
function image_hacker_enqueue_editor_assets() {
$asset_file = include( plugin_dir_path( __FILE__ ) . 'build/index.asset.php');
// Enqueue the script with our modifications
wp_enqueue_script(
'image-hacker-script',
plugins_url( 'build/index.js', __FILE__ ),
array( 'wp-plugins', 'wp-edit-post' ),
filemtime( plugin_dir_path( __FILE__ ) . 'build/index.js' )
);
// Enqueue the editor-only styles
wp_enqueue_style(
'image-hacker-editor-style',
plugins_url( 'build/editor.css', __FILE__ ),
[],
filemtime( plugin_dir_path( __FILE__ ) . 'build/editor.css' )
);
}
add_action( 'enqueue_block_editor_assets', 'image_hacker_enqueue_editor_assets' );
/**
* Enqueue frontend and editor assets.
*/
function image_hacker_enqueue_assets() {
$asset_file = include( plugin_dir_path( __FILE__ ) . 'build/index.asset.php');
// Enqueue styles for both frontend and editor
wp_enqueue_style(
'image-hacker-style',
plugins_url( 'build/style-index.css', __FILE__ ),
[],
filemtime( plugin_dir_path( __FILE__ ) . 'build/style-index.css' )
);
}
add_action( 'enqueue_block_assets', 'image_hacker_enqueue_assets' );

這段程式碼的作用如下:

  • enqueue_block_editor_assets 動作鉤子將 index.js 指令碼和 editor.css 檔案加入佇列。
  • enqueue_block_assets 動作鉤子將 style.css 檔案加入佇列。

請注意,這段程式碼包含位於外掛 /build/ 資料夾中的 .js.css 資源。這意味著,要使其正常工作,您需要在命令列工具中執行 build 命令:

npm run build

另請注意,當您將名為 style.scss 的檔案匯入 index.js 時,編譯後的 CSS 檔案將不再名為 style.css,而是 style-index.css

註冊區塊樣式

您已完成開發環境的設定。現在,您可以進入專案的精彩部分,註冊您的區塊樣式變體。

註冊區塊樣式的方法有很多種,您可以根據自己的目標和個人偏好進行選擇。我們將使用 JS 方法構建 Gutenberg 外掛。開啟您的 /src/index.js 檔案並貼上以下程式碼:

// Import the function to register block styles.
import { registerBlockStyle } from '@wordpress/blocks';
// Import the function to run code only when the DOM is ready.
import domReady from '@wordpress/dom-ready';
// This line tells the build process to include and compile our SCSS file.
import './style.scss';
/**
* Use domReady to run code only when the DOM is ready.
*/
domReady(() => {
// Register our new style variation for the core image block.
registerBlockStyle('core/image', {
name: 'polaroid',
label: 'Polaroid',
});
});

結合使用 registerBlockStyledomReady 可確保僅在 DOM 完全載入時註冊樣式變體。另請參閱官方文件

選擇 Polaroid 樣式後,WordPress 會自動將 .is-style-polaroid 類新增到區塊包裝器中。

下一步是提供樣式變體的 CSS。開啟 /src/style.scss 檔案並新增以下程式碼:

.wp-block-image.is-style-polaroid {
padding: 15px 15px 70px 15px;
background-color: white;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
max-width: 360px;
transform: rotate(-3deg);
transition: transform 0.3s ease-in-out;
figure { 
margin: 0 !important; 
}
img { 
display: block; 
width: 100%; 
height: auto; 
}
figcaption {
position: absolute; 
bottom: 15px; 
left: 0; 
right: 0;
text-align: center; 
font-family: 'Permanent Marker', cursive;
color: #333; 
font-size: 18px;
}
}

儲存程式碼,執行 npm run build,然後跳轉到 WordPress 資訊中心。建立一個新文章或頁面並新增圖片。選擇圖片後,點選區塊側邊欄中的“Styles”標籤,然後選擇“Polaroid”。

圖片區<mark class=

圖片區塊的新樣式變體

新增圖片說明文字,儲存文章,然後在前端檢視效果。您應該會看到一張帶有精美斜體標題的寶麗來風格圖片。

帶有 is_style_polaroid 類的 figure 元素

帶有 is_style_polaroid 類的 figure 元素

注:由於選擇器的高度特異性,某些屬性(例如 max-width )可能無法在編輯器中應用。如果您需要在編輯器中應用這些屬性,您可能需要在 editor.scss 檔案中新增適當的樣式。

構建邏輯

下一步是構建影像動畫的邏輯。我們將使用 CSS 的 transform 屬性建立一個簡單的動畫。首先,將以下程式碼區塊新增到 src/style.scss 檔案:

.wp-block-image.is-style-polaroid.has-image-animation:hover {
transform: rotate(0deg) scale(1.05);
}

這段程式碼確保僅當區塊是寶麗來影像且透過工具欄切換按鈕應用了 has-image-animation 類時,才會應用懸停效果。

現在,您需要將 CSS 類新增到影像容器(即 figure 元素)的邏輯。為此,您需要一些過濾器和回撥函式。

首先,將以下行新增到您的 src/index.js 檔案:

import { addFilter } from '@wordpress/hooks';

步驟 1. 向Image區塊新增新屬性

您將使用 addFilter 來操作核心 Image 區塊。首先,向 Image 區塊新增一個新的 imageAnimation 屬性:

function addImageAnimationAttribute( settings, name ) {
if ( name !== 'core/image' ) {
return settings;
}
settings.attributes = {
...settings.attributes,
imageAnimation: {
type: 'boolean',
default: false,
},
};
return settings;
}
addFilter(
'blocks.registerBlockType',
'image-hacker/add-image-animation-attribute',
addImageAnimationAttribute
);

回撥函式 addImageAnimationAttribute 接受兩個引數:

  • settings – 當前區塊屬性的陣列
  • name – 指定要修改其屬性的區塊的名稱。

然後,該函式返回更新後的屬性陣列。

步驟 2. 向影像區塊新增切換控制元件

接下來,您需要向影像區塊工具欄新增一個控制元件以啟用動畫。

首先,將以下匯入新增到 index.js 檔案:

import { createHigherOrderComponent } from '@wordpress/compose';
import { Fragment } from '@wordpress/element';
import { BlockControls } from '@wordpress/block-editor';
import { ToolbarGroup, ToolbarButton } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

然後在檔案末尾新增如下程式碼:

const withPolaroidControls = createHigherOrderComponent((BlockEdit) => {
return (props) => {
if (props.name !== 'core/image') {
return <BlockEdit {...props} />;
}
const { attributes, setAttributes, isSelected } = props;
const { imageAnimation, className, lightbox } = attributes;
return (
<Fragment>
<BlockEdit {...props} />
<BlockControls>
<ToolbarGroup>
<ToolbarButton
icon="format-image"
label={__('Toggle Animation', 'image-hacker')}
isActive={imageAnimation}
onClick={() =>
setAttributes({ imageAnimation: !imageAnimation })
}
/>
</ToolbarGroup>
</BlockControls>
</Fragment>
);
};
}, 'withPolaroidControls');
addFilter(
'editor.BlockEdit',
'image-hacker/with-polaroid-controls',
withPolaroidControls
);

這段程式碼的作用如下:

  • createHigherOrderComponent  函式建立一個高階元件 (HOC),該元件包裝了 BlockEdit,BlockEdit 是編輯器中負責顯示區塊的主要元件。
  • HOC 會攔截該元件並檢查它是否為影像區塊。這確保所有編輯操作都只應用於影像區塊。
  • 我們使用解構賦值從 propsattribute 物件中提取所需的屬性 (Property) 和特性 (Attribute)。
  • 我們使用 BlockControlsToolbarGroupToolbarButton 元件向區塊工具欄新增一個“切換動畫 (Toggle Animation)”按鈕。
  • isActive 設定 imageAnimation 的預設狀態。
  • onClick 切換 imageAnimation 的值。

自定義按鈕

區塊工具欄上已新增一個自定義按鈕。

現在您有了一個屬性和一個按鈕。但是,如果您點選該按鈕,什麼也沒有發生。

步驟 3. 將CSS類新增到包裝元素

下一步是將 has-image-animation 類應用於包裹影像的 figure 元素。為此,您需要一個過濾器,以便您在前端將 CSS 類分配給影像。

將以下程式碼附加到 index.js 檔案:

function addAnimationFrontendClass(extraProps, blockType, attributes) {
if (blockType.name === 'core/image' && attributes.imageAnimation) {
extraProps.className = `${extraProps.className || ''} has-image-animation`;
}
return extraProps;
}
addFilter(
'blocks.getSaveContent.extraProps',
'image-hacker/add-animation-frontend-class',
addAnimationFrontendClass
);

imageAnimation 屬性設定為 true 時,此程式碼會動態地將 CSS 類 has-image-animation 新增到 figure 元素。

讓我們嘗試瞭解具體發生了什麼。

  • addFilter 會掛接到編輯器的程序中,以修改資料或行為。
  • blocks.getSaveContent.extraProps 是我們要定位的特定鉤子。extraProps 是一個特殊的鉤子,可讓您向包裝器元素新增額外的 HTML 屬性。
  • image-hacker/add-animation-class 是過濾器的唯一名稱。
  • addAnimationFrontendClass  是每次執行 block.getSaveContent.extraProps 鉤子時執行的回撥函式的名稱。此函式接受 3 個引數:
    • extraProps:包含區塊包裝器元素屬性的物件,例如 className
    • blockType:包含區塊詳細資訊的物件,例如其 name( core/image )。
    • attributes:區塊屬性物件。
  • 該函式的邏輯確保程式碼僅在 blockType.name === 'core/image'attribute.imageAnimationtrue 時執行。
  • 如果兩個條件都成立,該函式將返回一個新的 props 物件,並將 has-image-animation 附加到現有的類物件上。

現在,您可以親自嘗試一下。在您的內容中新增一張圖片,從區塊側邊欄中選擇寶麗來風格,然後點選區塊工具欄中的“Toggle Animation(切換動畫)”按鈕。儲存您的文章並在前端檢查結果。當您將滑鼠懸停在圖片上時,圖片應該會旋轉。

is_style_polaroid 和 has_image_animation CSS 類

已將 is_style_polaroid 和 has_image_animation CSS 類新增到圖片區塊

註冊區塊變體

區塊變體是區塊的預配置版本,具有一組屬性和巢狀區塊。WordPress 將區塊變體視為獨立區塊,使其在區塊插入器中可用,並使用自定義圖示標記。

您可以使用區塊變體建立一個預設應用 Polaroid 樣式的新版本圖片區塊。

第一步是將 registerBlockVariation 函式匯入到您的 /src/index.js 檔案中:

import { registerBlockStyle, registerBlockVariation } from '@wordpress/blocks';

然後在 domReady() 內部的 registerBlockVariation 函式中新增對 registerBlockStyle 下方的呼叫:

domReady(() => {
// Register a style variation for the image block.
registerBlockStyle('core/image', {
name: 'polaroid',
label: 'Polaroid',
});
// Register a block variation of the image block
registerBlockVariation('core/image', {
name: 'animated-polaroid',
title: 'Animated Polaroid',
icon: 'image-filter',
attributes: {
className: 'is-style-polaroid',
imageAnimation: true,
},
scope: ['inserter'],
});
});

registerBlockVariation 函式為現有區塊建立變體。它接受兩個引數:區塊名稱和定義變體的物件。(另請參閱區塊變體簡介區塊變體 API 文件。)

儲存檔案,執行構建程式以應用更改,然後返回 WordPress 管理員頁面。建立新文章,並在區塊插入器中搜尋“Animated Polaroid”區塊。

區<mark class=

區塊插入器中的區塊變體

注:由於環境的複雜性和選擇器的特殊性,我們不會在區塊編輯器中新增生成動畫的程式碼。因此,動畫在編輯器中無法正常工作。

測試和除錯

讓我們進行一些測試。在新文章中新增一張或多張圖片。為每張圖片選擇寶麗來風格,啟用動畫並新增連結。同時,使用相簿區塊執行測試。

一切似乎都按預期執行。但是,將帶有燈箱效果的連結新增到寶麗來風格的圖片上,效果並不理想。

這種奇怪的行為似乎是由於 WordPress 燈箱效果和 CSS 過渡之間的相容性問題造成的。

為了避免漫長而複雜的除錯過程,您可能需要停用“點選放大”選項,並新增警告以通知使用者燈箱已停用。

首先,您需要匯入一些額外的資源。以下是從 /src/index.js 檔案匯入的資源的完整列表:

import { registerBlockStyle, registerBlockVariation } from '@wordpress/blocks';
import domReady from '@wordpress/dom-ready';
import { addFilter } from '@wordpress/hooks';
import { createHigherOrderComponent } from '@wordpress/compose';
import { Fragment, useEffect } from '@wordpress/element';
import { InspectorControls, BlockControls } from '@wordpress/block-editor';
import { PanelBody, Notice, ToolbarGroup, ToolbarButton } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useDispatch } from '@wordpress/data';
import './style.scss';

我們新增了以下匯入:

  • useEffect 來自 @wordpress/element。(參見文件
  • InspectorControls 來自 @wordpress/block-editor (參見文件)。
  • PanelBodyNotice 來自 @wordpress/components(參見文件)。
  • useDispatch 來自 @wordpress/data。(參見 WordPress 開發者部落格)。

現在將 withPolaroidControls 函式修改如下:

const withPolaroidControls = createHigherOrderComponent((BlockEdit) => {
return (props) => {
if (props.name !== 'core/image') {
return <BlockEdit {...props} />;
}
const { attributes, setAttributes, isSelected } = props;
const { imageAnimation, className, lightbox } = attributes;
const isPolaroid = className?.includes('is-style-polaroid');
const { createNotice } = useDispatch('core/notices');
useEffect(() => {
if (isPolaroid && lightbox?.enabled) {
// Disable the lightbox to prevent the conflict.
setAttributes({ lightbox: { ...lightbox, enabled: false } });
// Show the user a temporary 'snackbar' notice.
createNotice(
'warning', // The type of notice (info, success, warning, error)
__('Lightbox disabled for Polaroid style.', 'image-hacker'),
{
type: 'snackbar',
isDismissible: true,
}
);
}
}, [isPolaroid, lightbox]);
return (
<Fragment>
<BlockEdit {...props} />
<BlockControls>
<ToolbarGroup>
<ToolbarButton
icon="format-image"
label={__('Toggle Animation', 'image-hacker')}
isActive={imageAnimation}
onClick={() =>
setAttributes({ imageAnimation: !imageAnimation })
}
/>
</ToolbarGroup>
</BlockControls>
{isSelected && isPolaroid && (
<InspectorControls>
<PanelBody title={__('Polaroid Style', 'image-hacker')}>
<Notice status="info" isDismissible={false}>
{__(
'The "Expand on click" (lightbox) feature is disabled for this style to prevent visual conflicts.',
'image-hacker'
)}
</Notice>
</PanelBody>
</InspectorControls>
)}
</Fragment>
);
};
}, 'withPolaroidControls');
  • useEffect  是一個 React Hook,它“允許你將元件與外部系統同步”。該程式碼在元件渲染完成後以及每次依賴項陣列 [isPolaroid, lightbox] 中的值發生變化時執行。僅當使用者應用或移除寶麗來樣式,或者啟用或停用燈箱時,才會執行檢查。(請參閱 React 文件。)
  • 條件 if (isPolaroid() && lightbox.enabled) 確保僅當影像具有寶麗來樣式且燈箱選項啟用時,程式碼才會執行。
  • 如果條件為 true,則燈箱將被停用,並顯示臨時警告通知。(另請參閱通知資料參考。)
  • 條件 isSelected && isPolaroid 會在影像區塊工具欄中生成一個新面板,通知使用者燈箱已被停用。與 Snackbar 不同,此面板顯示永久警告。

單擊放大選項已被停用

單擊放大選項已被停用。

小結

在本教程中,我們透過一個實際專案的視角,深入探討了 WordPress 區塊編輯器中一些最令人興奮、最強大的開發者功能:我們擴充套件了核心圖片區塊,使其具備開箱即用的功能,並新增了自定義樣式和動畫效果。

我們採用漸進式增強方法,為圖片區塊設計了區塊樣式變體。這讓使用者可以輕鬆地將圖片賦予經典的寶麗來風格。

接下來,我們在圖片區塊的工具欄中新增了一個專用按鈕,方便使用者建立引人入勝的懸停動畫效果。

最後,我們建立了一個區塊變體,並預設應用了寶麗來樣式和動畫設定,為整個教程畫上了圓滿的句號。

我們希望您從本教程中獲得的見解和技巧能夠幫助您為 Gutenberg 的核心區塊建立出一些真正令人驚喜的自定義功能!

Happy coding!

評論留言