
區塊繫結 API 是區塊編輯器中一個強大的工具,它允許您將任何資料來源連線到區塊的屬性。
此 API 最初在 WordPress 6.5 中引入,其最初的實現方式是讓 WordPress 使用者能夠在文章和頁面中顯示自定義欄位值。
區塊繫結 API 是其他強大 WordPress 功能的基礎。例如,同步樣板覆蓋和 WordPress 6.9 中引入的“文章日期”區塊變體。
那麼,區塊繫結 API 究竟是什麼?它有什麼用途?我們將提供一個簡單的介紹和一個實際示例,展示如何在 Gutenberg 區塊和外部資料來源之間建立繫結。
區塊繫結API:基本概念
如上所述,區塊繫結 API 允許您在資料來源和區塊屬性之間建立繫結。
如果您不熟悉區塊屬性,請導航至 GitHub 上 Gutenberg 專案區塊庫的 src 目錄,找到“段落”區塊,然後開啟 block.json 檔案。attributes 屬性提供了“段落”區塊屬性的列表。
"attributes": {
"content": {
"type": "rich-text",
"source": "rich-text",
"selector": "p",
"role": "content"
},
"dropCap": {
"type": "boolean",
"default": false
},
"placeholder": {
"type": "string"
},
"direction": {
"type": "string",
"enum": [ "ltr", "rtl" ]
}
},
以下區塊自 WordPress 6.9 起支援區塊繫結 API,因此可以連結到您的自定義欄位:
| 支援的區塊 | 屬性 |
|---|---|
| 段落 | content |
| 標題 | content |
| 圖片 | id, url, alt, title, caption |
| 按鈕 | text, url, linkTarget, rel |
要將自定義欄位連線到 Gutenberg 區塊,您必須先註冊它們。以下程式碼透過 WordPress 外掛或主題的 functions.php 檔案註冊自定義欄位:
add_action( 'init', function() {
register_post_meta( 'your-post-type', 'myplugin_meta_key', [
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'description' => __( 'City name', 'textdomain' ),
'auth_callback' => 'is_user_logged_in',
] );
} );
屬性定義了自定義欄位的特徵,文件中提供了完整的屬性列表。要使自定義欄位可供 Block Bindings API 使用,必須將 show_in_rest 設定為 `true`。從 WordPress 6.9 開始,string 是唯一受支援的型別。
要檢視 Block Bindings API 如何與自定義欄位配合使用,請建立一個新的 WordPress 外掛,並使用上述程式碼註冊一個元欄位。
<?php
/**
* Plugin Name: Block Bindings example
* Description: Example plugin that uses the Block Bindings API.
* Version: 1.0.0
* Author: Your Name
* License: GPL2 or later
* Text Domain: block-bindings-example
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action( 'init', function() {
register_post_meta( '', 'block_bindings_image_url', [
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'description' => __( 'City name', 'block-bindings-example' ),
'auth_callback' => 'is_user_logged_in',
] );
} );
在 WordPress 控制面板中啟用該外掛。然後,導航至“文章”頁面並建立一個新文章。當您選擇一個受支援的區塊時,“區塊設定”側邊欄中的“屬性”面板將顯示可繫結到已註冊自定義欄位的屬性列表。

支援區塊繫結的影像區塊屬性
開啟右上角的“選項”選單,選擇“首選項”。在“常規”選項卡中,找到“高階”部分並啟用自定義欄位。儲存更改,等待頁面重新載入,然後返回編輯器。

在編輯器的“首選項”中啟用自定義欄位。
注:我們假設您希望手動新增自定義欄位。本文不涉及如何建立簡化自定義欄位插入的介面。
下一步是插入一個影像區塊。選中該影像區塊後,點選“屬性”面板中的“+”圖示,然後選擇“url”屬性。“屬性”面板將顯示可用元欄位列表。再次選擇“url”。現在,您將看到當前文章型別可用的元欄位列表。

在“區塊繫結”介面中,將自定義欄位繫結到影像區塊的 URL 屬性。
選擇您的元欄位並儲存文章。現在您應該可以在編輯器和前端看到您的影像。

一個圖片區塊,其 url 屬性繫結到自定義欄位值。
從 WordPress 6.7 版本開始,您可以使用 Label 屬性在編輯器介面中顯示文字。以下程式碼區塊展示了一個示例:
add_action( 'init', function() {
register_post_meta( '', 'block_bindings_image_url', [
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'description' => __( 'City image', 'block-bindings-example' ),
'label' => __('Image URL'),
'auth_callback' => 'is_user_logged_in',
] );
} );

區塊繫結介面中的自定義欄位標籤
開啟程式碼編輯器後,您可以在圖片區塊分隔符內看到一個 JSON 物件。 metadata.bindings.url 屬性表明影像區塊的 url 連結到後設資料欄位。
<!-- wp:image {
"metadata":{
"bindings":{
"url":{
"source":"core/post-meta",
"args":{
"key":"block_bindings_image_url"
}
}
}
}
} -->
<figure class="wp-block-image"><img alt="/></figure>
<!-- /wp:image -->
source 屬性指定區塊繫結的資料來源。args.key 屬性建立對元欄位的引用。
區塊繫結 API 最吸引人的地方在於它能夠註冊自定義資料來源,這為開發者開啟了許多令人興奮的新可能性。接下來,我們將探討如何將第三方服務的資料與區塊繫結 API 結合使用。
如何註冊自定義區塊繫結資料來源:一個實際示例
熟悉 Block Bindings API 的基本概念後,我們可以繼續探討其更高階、更有趣的開發者功能。
如前所述,Block Bindings API 允許您註冊自定義資料來源。這使您可以從遠端源檢索資料,和/或處理原始資料以生成可自動插入到內容中的有用資訊。
在本節中,您將透過一個實際示例學習如何最大限度地發揮 Block Bindings 的潛力,該示例可作為開發您自己的自定義應用程式的基礎。
溫馨提示:請注意,以下示例中提供的程式碼僅用於演示目的,不應在生產環境中使用。
假設您想要從外部源檢索資料並將其顯示在您的文章、頁面或自定義文章型別中。例如,您可以透過傳送包含城市經緯度的請求來查詢天氣服務 API,以獲取即時天氣資料,然後將其顯示在您的網站上。
藉助 Block Bindings API,您可以顯示當前溫度或為讀者提供未來幾天的天氣預報。您還可以根據天氣情況,以程式設計方式更改頁面上一個或多個影像的 url 屬性。
要將此功能新增到您的 WordPress 網站,您需要建立一個外掛。請按照以下步驟操作:
步驟 1:建立基本外掛
第一步是建立外掛檔案。導航到 WordPress 安裝目錄下的 wp-content/plugins 目錄,並建立一個名為 block-bindings-example 的新資料夾。在該資料夾中,新增以下檔案:
/wp-content/plugins/ └── /block-bindings-example/ ├── block-bindings-example.php └── /includes/ ├── binding-sources.php ├── meta-fields.php └── weather-api.php
在您喜歡的程式碼編輯器中開啟 block-bindings-example.php 檔案,並新增以下程式碼:
<?php
/**
* Plugin Name: Block Bindings Example
* Description: Use WordPress Block Bindings API (6.5+) to dynamically bind weather data from Open-Meteo API to Gutenberg blocks using custom post meta and a custom binding source.
* Version: 1.0.0
* Author: Your Name
* License: GPL2 or later
* Text Domain: block-bindings-example
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Cache duration for weather data: 30 minutes
* This reduces API calls and improves performance
*/
define( 'BB_WEATHER_CACHE_TIME', HOUR_IN_SECONDS / 2 );
require_once plugin_dir_path( __FILE__ ) . 'includes/meta-fields.php';
require_once plugin_dir_path( __FILE__ ) . 'includes/binding-sources.php';
require_once plugin_dir_path( __FILE__ ) . 'includes/weather-api.php';
/**
* Setup function
*/
function bb_init_setup() {
bb_register_post_meta();
bb_register_binding_sources();
}
add_action( 'init', 'bb_init_setup' );
這段程式碼的作用如下:
- 常量
BB_WEATHER_CACHE_TIME決定了天氣資料的快取時長。這可以減少 API 呼叫次數,提升頁面效能,並降低服務成本。 -
require_once表示式包含了註冊元欄位、註冊繫結源以及從 API 獲取資料所需的指令碼。 - setup 函式呼叫了兩個函式,分別用於註冊文章元欄位和自定義繫結源。
步驟 2:註冊文章元欄位
下一步是註冊您所需的元欄位。開啟 includes 資料夾中的 meta-fields.php 檔案,並新增以下程式碼:
<?php
/**
* Registers custom post meta fields so they appear in the REST API and Block Bindings editor panel
*/
function bb_register_post_meta() {
if ( ! function_exists( 'register_post_meta' ) ) {
return;
}
register_post_meta( 'post', 'block_bindings_city_name', [
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'description' => __( 'Add city name', 'block-bindings-example' ),
'label' => __( 'City name', 'block-bindings-example' ),
'auth_callback' => 'is_user_logged_in',
] );
register_post_meta( 'post', 'block_bindings_image_url', [
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'description' => __( 'Add city image URL', 'block-bindings-example' ),
'label' => __( 'City image URL', 'block-bindings-example' ),
'auth_callback' => 'is_user_logged_in',
] );
register_post_meta( 'post', 'block_bindings_city_lat', [
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'description' => __( 'Add city latitude', 'block-bindings-example' ),
'label' => __( 'Latitude', 'block-bindings-example' ),
'auth_callback' => 'is_user_logged_in',
] );
register_post_meta( 'post', 'block_bindings_city_lng', [
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'description' => __( 'Add city longitude', 'block-bindings-example' ),
'label' => __( 'Longitude', 'block-bindings-example' ),
'auth_callback' => 'is_user_logged_in',
] );
}
register_post_meta 函式用於註冊文章中使用的元鍵。請注意,要使用透過這種方式註冊的元欄位訪問 Block Bindings API,您必須將 show_in_rest 設定為 true,並將 type 設定為 string。更多資訊請參閱文件。
步驟 3:註冊區塊繫結源
現在需要註冊您的區塊繫結源。開啟 binding-sources.php 檔案並新增以下程式碼:
<?php
/**
* Registers a custom Block Bindings source: bb/weather-condition
*/
function bb_register_binding_sources() {
if ( ! function_exists( 'register_block_bindings_source' ) ) {
return;
}
register_block_bindings_source(
'bb/weather-condition',
[
'label' => __( 'Weather Condition', 'block-bindings-example' ),
'get_value_callback' => 'bb_get_weather_condition_value',
'uses_context' => [ 'postId' ], // We need postId to get meta values
]
);
}
register_block_bindings_source() 函式需要一個資料來源名稱和一個回撥函式,該回撥函式用於從資料來源檢索資料並返回處理後的值。
然後,在同一個 binding-sources.php 檔案中定義回撥函式。
function bb_get_weather_condition_value( array $source_args, WP_Block $block_instance ) {
$key = $source_args['key'] ?? null;
if ( ! $key ) {
return null;
}
// Get current post ID from block context (always available in post content)
$post_id = $block_instance->context['postId'] ?? null;
// Fallback: use global loop if context is missing
if ( ! $post_id && in_the_loop() ) {
$post_id = get_the_ID();
}
if ( ! $post_id || $post_id <= 0 ) {
error_log( 'BB DEBUG: Could not determine post ID for weather binding' );
return null;
}
$weather_data = bb_fetch_and_cache_weather_data( $post_id );
if ( ! is_array( $weather_data ) || ! isset( $weather_data[ $key ] ) ) {
return null;
}
$value = $weather_data[ $key ];
// Append °C symbol for temperature
if ( $key === 'temperature' ) {
return $value . '°C';
}
return $value;
}
讓我們來分析一下這個函式:
$source_args['key']用於標識繫結到區塊屬性的資料。- 下一行從
context中檢索當前帖子的 ID。如果context缺失(例如預覽帖子),則使用get_the_ID()函式檢索當前帖子的 ID。 - 然後,它呼叫
bb_fetch_and_cache_weather_data函式,該函式從 API 獲取資料。我們將在下一步定義此函式。 $weather_data[$key]包含 API 提供的資料,例如溫度和天氣狀態。- 如果鍵是
temperature,則在提供的值後附加°C。 - 然後,該函式返回最終值。
步驟 4:從外部源檢索資料
如上所述,我們從 OpenMeteo 服務(免費用於非商業用途)檢索資料。
要獲取當前溫度和天氣狀況,您需要向 API 傳送一個請求,其中包含給定位置的緯度和經度,以及查詢引數 var current=weather_code,temperature_2m。以下是一個請求示例:
https://api.open-meteo.com/v1/forecast?latitude=-33.8717&longitude=151.2299¤t=weather_code,temperature_2m
API 會提供類似於以下內容的響應:
{
"latitude": -33.8717,
"longitude": 151.2299,
"generationtime_ms": 0.030875205993652344,
"utc_offset_seconds": 0,
"timezone": "GMT",
"timezone_abbreviation": "GMT",
"elevation": 13.0,
"current_units": {
"time": "iso8601",
"interval": "seconds",
"weather_code": "wmo code",
"temperature_2m":"°C"
},
"current": {
"time": "2025-12-01T16:00",
"interval": 900,
"weather_code": 3,
"temperature_2m":7.3
}
}

在 Postman for Visual Studio Code 中獲取 OpenMeteo 的響應
現在您已經知道如何獲取所需資料,請開啟 weather-api.php 檔案並新增以下程式碼:
function bb_fetch_and_cache_weather_data( $post_id ) {
$lat = get_post_meta( $post_id, 'block_bindings_city_lat', true );
$lng = get_post_meta( $post_id, 'block_bindings_city_lng', true );
$lat = str_replace( ',', '.', trim( $lat ) );
$lng = str_replace( ',', '.', trim( $lng ) );
if ( ! is_numeric( $lat ) || ! is_numeric( $lng ) ) {
error_log( 'BB DEBUG: Invalid latitude/longitude values after normalization' );
return false;
}
$transient_key = 'bb_weather_data_' . $post_id;
$cached_data = get_transient( $transient_key );
if ( $cached_data !== false ) {
error_log( "BB DEBUG: Cache hit for post ID {$post_id}" );
return $cached_data;
}
// Build Open-Meteo API URL
$api_url = sprintf(
'https://api.open-meteo.com/v1/forecast?latitude=%s&longitude=%s¤t=weather_code,temperature_2m',
rawurlencode( $lat ),
rawurlencode( $lng )
);
error_log( "BB DEBUG: Fetching weather data from: {$api_url}" );
$response = wp_remote_get( $api_url, [ 'timeout' => 10 ] );
if ( is_wp_error( $response ) ) {
error_log( 'BB DEBUG: API request failed – ' . $response->get_error_message() );
return false;
}
if ( wp_remote_retrieve_response_code( $response ) !== 200 ) {
error_log( 'BB DEBUG: API returned non-200 status code' );
return false;
}
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body, true );
if ( ! $data || ! isset( $data['current'] ) ) {
error_log( 'BB DEBUG: Invalid or empty API response' );
return false;
}
$temperature = $data['current']['temperature_2m'] ?? null;
$weather_code = $data['current']['weather_code'] ?? 0;
$mapped_data = [
'temperature' => round( (float) $temperature ),
'weather_state' => bb_map_wmo_code_to_state( (int) $weather_code ),
];
// Cache for 30 minutes
set_transient( $transient_key, $mapped_data, BB_WEATHER_CACHE_TIME );
error_log( 'BB DEBUG: Weather data fetched and cached successfully' );
return $mapped_data;
}
此函式從 OpenMeteo API 獲取當前天氣資料,並使用瞬態資料將其儲存在快取中。讓我們仔細看看。
- 兩次呼叫
get_post_meta函式獲取您所在位置的緯度和經度。 - 以下兩行程式碼規範化小數分隔符,以防使用者輸入逗號而不是句點。
- 條件語句區塊使用
is_numeric()函式檢查值是否為數值格式。 - 接下來,它檢查資料是否在快取中。如果在,則返回快取資料並停止函式,而不向 API 傳送任何請求。
- 如果在快取中找不到資料,則構建請求並儲存響應。
- 以下幾行程式碼提供
temperature和weather_code。 weather_code透過下面定義的bb_map_wmo_code_to_state函式對映到weather_state。- 資料使用
set_transient函式儲存。 - 最後,該函式返回對映後的資料。
最後,定義將 weather_code 轉換為人類可讀字串的函式:
function bb_map_wmo_code_to_state( $code ) {
if ( $code >= 0 && $code <= 3 ) {
return 'clear';
} elseif ( $code >= 51 && $code <= 67 ) {
return 'rainy';
} elseif ( $code >= 71 && $code <= 77 ) {
return 'snowy';
} elseif ( $code >= 95 ) {
return 'thunderstorm';
}
return 'cloudy';
}
程式碼已完成,您的外掛已準備好進行測試。
如何使用Block Bindings API
現在是時候學習如何使用透過 Block Bindings API 新增到您網站的新功能了!
在 WordPress 控制面板中,導航至“外掛”頁面,並啟用您剛剛建立的 Block Bindings Example 外掛。

在 WordPress 控制面板中啟用外掛。
之後,建立一個新文章或頁面。新增一個圖片區塊、一個標題和四個行區塊,每個行區塊包含兩個段落,如下圖所示。然後,儲存文章。

將區塊新增到編輯器畫布。
接下來,新增自定義欄位並再次儲存文章。

向文章新增自定義欄位。
選擇圖片區塊,然後在“區塊設定”側邊欄中找到“屬性”面板。點選“+”按鈕開啟下拉選單,其中顯示了支援區塊繫結的圖片區塊屬性列表。選擇“url”項。

支援區塊繫結的圖片區塊屬性
選擇區塊屬性後,“高階”選項卡將顯示一個新的“URL”元素,其描述為“Not connected”。再次點選“url”項以檢視可用繫結源列表。“文章後設資料”提供了為文章型別註冊的四個自定義欄位及其各自的值。選擇“City Image URL”。

連線已註冊的元欄位。
您已將“City Image URL”元欄位分配給“影像”區塊的 url 屬性。現在您應該可以看到所選城市的圖片。
對其他元欄位執行相同的操作。將“City Name”欄位分配給“標題”區塊的 content 屬性,並將“Latitude”和“Longitude”欄位分配給相應的“段落”區塊。
現在,將最後兩個區塊連線到您的自定義繫結源。遺憾的是,正如您在之前的螢幕截圖中看到的,此選項在編輯器 UI 中不可用。
目前,您需要切換到程式碼編輯器,並手動編寫連結到繫結源的兩個區塊的標記。以下是顯示 OpenMeteo 服務提供的溫度的程式碼:
<!-- wp:paragraph {
"metadata":{
"bindings":{
"content":{
"source":"bb/weather-condition",
"args":{
"key":"temperature"
}
}
}
}
} -->
<p>Placeholder</p>
<!-- /wp:paragraph -->
使用此方法,您的繫結資料來源名稱在編輯器中將顯示為“Weather Condition”,但實際資料僅在前端可見。

自定義資料來源的區塊繫結示例
顯然,手動將 JSON 物件新增到區塊標記中並非易事。幸運的是,WordPress 6.9 對區塊繫結 API 進行了重大改進,使得為自定義資料來源建立使用者介面成為可能。讓我們嘗試使用自定義使用者介面來改進我們的外掛。
如何為自定義區塊繫結資料來源建立使用者介面
注:我們推遲了專案的這一部分,因為所需的功能僅在 WordPress 6.9 及更高版本中可用。如果您執行的是早期版本的 WordPress,以下程式碼將無法工作。
要為自定義繫結資料來源建立使用者介面,您需要編寫一些 JavaScript 程式碼。首先,在 /includes 目錄下建立一個 js 子資料夾,然後在其中建立一個名為 block-bindings-ui.js 的檔案。外掛結構現在如下:
/wp-content/plugins/ └── /block-bindings-example/ ├── block-bindings-example.php └── /includes/ ├── binding-sources.php ├── meta-fields.php └── weather-api.php └── /js/ └── block-bindings-ui.js
首先,將JS指令碼新增到外掛的主檔案中:
function bb_enqueue_weather_bindings_ui() {
if ( ! function_exists( 'register_block_bindings_source' ) ) {
return;
}
$js_file_path = plugin_dir_path( __FILE__ ) . 'includes/js/block-bindings-ui.js';
if ( ! file_exists( $js_file_path ) ) {
return;
}
// Enqueue the script only in the editor
wp_enqueue_script(
'bb-weather-bindings-ui',
plugin_dir_url( __FILE__ ) . 'includes/js/block-bindings-ui.js',
[ 'wp-blocks', 'wp-element', 'wp-dom-ready', 'wp-block-bindings' ],
filemtime( $js_file_path ),
true
);
}
add_action( 'enqueue_block_editor_assets', 'bb_enqueue_weather_bindings_ui' );
此函式的功能如下:
- 首先,它檢查
register_block_bindings_source()函式是否存在。 - 其次,它檢查外掛的
/includes/js資料夾中是否存在block-bindings-ui.js檔案。 wp_enqueue_script()函式會將指令碼加入編輯器的佇列。有關此函式的詳細說明,請參閱文件。- 它使用
enqueue_block_editor_assets鉤子將指令碼加入編輯介面的佇列。
現在開啟 block-bindings-ui.js 檔案並編寫以下程式碼:
wp.blocks.registerBlockBindingsSource({
name: 'bb/weather-condition',
label: 'Weather Condition',
useContext: [ 'postId', 'postType' ],
getValues: ( { bindings } ) => {
if ( bindings.content?.args?.key === 'temperature' ) {
return {
content: 'Current temperature provided by Open-Meteo.',
};
}
if ( bindings.content?.args?.key === 'weather_state' ) {
return {
content: 'Current conditions.',
};
}
return {
content: bindings.content,
};
},
getFieldsList() {
return [
{ label: 'Temperature (°C)', type: 'string', args: { key: 'temperature' } },
{ label: 'Weather Conditions', type: 'string', args: { key: 'weather_state' } }
];
}
});
registerBlockBindingsSource()函式用於在區塊編輯器中註冊繫結源。name是繫結源的唯一識別符號。它必須與 PHP 中register_block_bindings_source()函式使用的名稱完全一致。label是一個易於理解的名稱,顯示在“屬性”面板的“來源”下拉式清單中。useContext設定此來源需要從區塊中獲取的上下文值。postId是必需的,以便來源知道要讀取哪個帖子的後設資料/天氣資料。getValues提供區塊編輯器中繫結值的預覽。它返回使用者選擇繫結源(在本例中為“天氣狀況”)後下拉式清單中顯示的選項。此方法自 WordPress 6.9 起可用。getFieldsList返回使用者選擇繫結源(在本例中為“天氣狀況”)後下拉式清單中顯示的選項。
儲存檔案並返回編輯器。您的“天氣狀況”資料來源現已顯示在編輯器介面中,與“文章後設資料”並列。重新載入頁面,然後將段落或標題區塊連線到您的繫結資料來源。下圖顯示了結果。

自定義區塊繫結源 UI
最終影像展示了網站前端的顯示效果。

一篇展示來自外部繫結源資料的帖子
您還可以使用Block Bindings API做什麼?
本文僅淺嘗輒止地介紹了 Block Bindings API 的強大功能。值得一提的是,這項強大的 WordPress 功能的開發遠未結束,未來我們有望看到更多新的實現和新增功能。
將 Block Bindings API 與其他強大的 WordPress API(例如 Interactivity API)整合,您可以構建動態的互動式應用程式,其功能遠超 WordPress 早期賴以成名的傳統部落格功能。
WordPress 不再僅僅是一個部落格平臺或網站構建器。它正朝著成為適用於各種型別 Web 應用程式的多用途開發平臺的目標邁進。

評論留言