如何建立WordPress區塊模板

如何建立WordPress區塊模板

古騰堡時代,設計過程與 WordPress 主題沒有嚴格的聯絡。開箱即用的內容管理系統為使用者提供了構建優秀網站佈局所需的所有設計工具,而主題的目標是增加更多的構建和設計工具。

區塊模板是一種可以釋放更多網站構建能力的功能。根據區塊編輯器手冊

區塊模板被定義為區塊專案列表。這些區塊可以有預定義的屬性、佔位符內容,也可以是靜態或動態的。區塊模板允許為編輯器會話指定預設初始狀態。

換句話說,區塊模板是預製的區塊集合,用於在客戶端動態設定預設狀態。

👉 區塊模板不同於模板檔案。

模板檔案是 PHP 檔案,如 index.phppage.phpsingle.php,根據 WordPress 模板層次結構,經典主題和區塊主題的工作方式相同。在經典主題中,這些檔案是用 PHP 和 HTML 編寫的。在區塊主題中,這些檔案完全由塊構成。

👉 區塊模板不同於區塊樣板。

區塊樣板需要手動新增到頁面中,而區塊模板會在您或您的團隊成員建立新文章時自動提供初始佈局和預設值。

您還可以將特定的區塊模板繫結到自定義文章型別,並鎖定某些區塊或功能,以強制使用者使用預設設定或防止出錯。

建立區塊模板有幾種方法。您可以使用區塊 API 通過 PHP 宣告區塊型別陣列,也可以使用 InnerBlocks 元件建立自定義區塊型別。

如何使用 PHP 建立區塊模板

如果你是老派開發人員,可以使用外掛或主題的 functions.php 定義自定義區塊模板。如果您決定使用外掛,請啟動您最喜歡的程式碼編輯器,建立一個新的 PHP 檔案,然後新增以下程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
/*
* Plugin Name: My Block Templates
* Plugin URI: https://example.com/
* Description: An example plugin
* Version: 1.0
* Requires at least: 5.5
* Requires PHP: 8.0
* Author: Your name
* Author URI: https://author.example.com/
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Update URI: https://example.com/my-plugin/
*/
function myplugin_register_my_block_template() {
$post_type_object = get_post_type_object( 'post' );
$post_type_object->template = array(
array( 'core/image' ),
array( 'core/heading' ),
array( 'core/paragraph' )
);
}
add_action( 'init', 'myplugin_register_my_block_template' );
<?php /* * Plugin Name: My Block Templates * Plugin URI: https://example.com/ * Description: An example plugin * Version: 1.0 * Requires at least: 5.5 * Requires PHP: 8.0 * Author: Your name * Author URI: https://author.example.com/ * License: GPL v2 or later * License URI: https://www.gnu.org/licenses/gpl-2.0.html * Update URI: https://example.com/my-plugin/ */ function myplugin_register_my_block_template() { $post_type_object = get_post_type_object( 'post' ); $post_type_object->template = array( array( 'core/image' ), array( 'core/heading' ), array( 'core/paragraph' ) ); } add_action( 'init', 'myplugin_register_my_block_template' );
<?php
/*
* Plugin Name:       My Block Templates
* Plugin URI:        https://example.com/
* Description:       An example plugin
* Version:           1.0
* Requires at least: 5.5
* Requires PHP:      8.0
* Author:            Your name
* Author URI:        https://author.example.com/
* License:           GPL v2 or later
* License URI:       https://www.gnu.org/licenses/gpl-2.0.html
* Update URI:        https://example.com/my-plugin/
*/
function myplugin_register_my_block_template() {
$post_type_object = get_post_type_object( 'post' );
$post_type_object->template = array(
array( 'core/image' ),
array( 'core/heading' ),
array( 'core/paragraph' )
);
}
add_action( 'init', 'myplugin_register_my_block_template' );

在上述程式碼中, get_post_type_object 按名稱檢索文章型別。

將檔案儲存在 wp-content/plugins 資料夾中,進入 WordPress 面板中的外掛介面,啟用 My Block Templates 外掛。

現在,當你建立一篇新文章時,編輯器會自動啟動包含圖片塊、標題和段落的塊模板。

在帖子編輯器中自動載入區塊模板

在帖子編輯器中自動載入區塊模板

您還可以為每個區塊新增設定陣列,並建立巢狀的區塊結構。下面的函式建立了一個包含內部區塊和設定的更高階的區塊模板:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function myplugin_register_my_block_template() {
$block_template = array(
array( 'core/image' ),
array( 'core/heading', array(
'placeholder' => 'Add H2...',
'level' => 2
) ),
array( 'core/paragraph', array(
'placeholder' => 'Add paragraph...'
) ),
array( 'core/columns',
array(),
array(
array( 'core/column',
array(),
array(
array( 'core/image' )
)
),
array( 'core/column',
array(),
array(
array( 'core/heading', array(
'placeholder' => 'Add H3...',
'level' => 3
) ),
array( 'core/paragraph', array(
'placeholder' => 'Add paragraph...'
) )
)
)
)
)
);
$post_type_object = get_post_type_object( 'post' );
$post_type_object->template = $block_template;
}
add_action( 'init', 'myplugin_register_my_block_template' );
function myplugin_register_my_block_template() { $block_template = array( array( 'core/image' ), array( 'core/heading', array( 'placeholder' => 'Add H2...', 'level' => 2 ) ), array( 'core/paragraph', array( 'placeholder' => 'Add paragraph...' ) ), array( 'core/columns', array(), array( array( 'core/column', array(), array( array( 'core/image' ) ) ), array( 'core/column', array(), array( array( 'core/heading', array( 'placeholder' => 'Add H3...', 'level' => 3 ) ), array( 'core/paragraph', array( 'placeholder' => 'Add paragraph...' ) ) ) ) ) ) ); $post_type_object = get_post_type_object( 'post' ); $post_type_object->template = $block_template; } add_action( 'init', 'myplugin_register_my_block_template' );
function myplugin_register_my_block_template() {
$block_template = array(
array( 'core/image' ),
array( 'core/heading', array(
'placeholder'	=> 'Add H2...',
'level'			=> 2
) ),
array( 'core/paragraph', array(
'placeholder'	=> 'Add paragraph...'
) ),
array( 'core/columns', 
array(), 
array( 
array( 'core/column',
array(),
array(
array( 'core/image' )
)
), 
array( 'core/column',
array(),
array(
array( 'core/heading', array(
'placeholder'	=> 'Add H3...',
'level'			=> 3
) ),
array( 'core/paragraph', array(
'placeholder'	=> 'Add paragraph...'
) )
) 
)
) 
)
);
$post_type_object = get_post_type_object( 'post' );
$post_type_object->template = $block_template;
}
add_action( 'init', 'myplugin_register_my_block_template' );

您可以在下圖中看到上述程式碼的輸出結果:

更高階的區塊模板

更高階的區塊模板

到目前為止,我們只使用了核心區塊。但你也可以在區塊模板中加入自定義區塊區塊樣板,如下例所示:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function myplugin_register_my_block_template() {
$post_type_object = get_post_type_object( 'page' );
$post_type_object->template = array(
array( 'core/pattern', array(
'slug' => 'my-plugin/my-block-pattern'
) )
);
}
add_action( 'init', 'myplugin_register_my_block_template' );
function myplugin_register_my_block_template() { $post_type_object = get_post_type_object( 'page' ); $post_type_object->template = array( array( 'core/pattern', array( 'slug' => 'my-plugin/my-block-pattern' ) ) ); } add_action( 'init', 'myplugin_register_my_block_template' );
function myplugin_register_my_block_template() {
$post_type_object = get_post_type_object( 'page' );
$post_type_object->template = array(
array( 'core/pattern', array(
'slug' => 'my-plugin/my-block-pattern'
) ) 
);
}
add_action( 'init', 'myplugin_register_my_block_template' );

如果您決定為已註冊的自定義帖子型別建立一個預設的區塊模板,這兩者並無太大區別。只需將 get_post_type_object 的帖子型別改為自定義帖子型別名稱即可,如下例所示:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
function myplugin_register_my_block_template() {
$post_type_object = get_post_type_object( 'book' );
$post_type_object->template = array(
array( 'core/image' ),
array( 'core/heading' ),
array( 'core/paragraph' )
);
}
add_action( 'init', 'myplugin_register_my_block_template' );
<?php function myplugin_register_my_block_template() { $post_type_object = get_post_type_object( 'book' ); $post_type_object->template = array( array( 'core/image' ), array( 'core/heading' ), array( 'core/paragraph' ) ); } add_action( 'init', 'myplugin_register_my_block_template' );
<?php
function myplugin_register_my_block_template() {
$post_type_object = get_post_type_object( 'book' );
$post_type_object->template = array(
array( 'core/image' ),
array( 'core/heading' ),
array( 'core/paragraph' )
);
}
add_action( 'init', 'myplugin_register_my_block_template' );

既然你已經知道如何建立區塊模板,我們就可以繼續探索更多的使用案例。讓我們深入探討一下。

  1. 使用自定義帖子型別的區塊模板
  2. 利用區塊屬性微調區塊模板
  3. 鎖定區塊
  4. 防止使用者解鎖區塊
  5. 禁用特定使用者角色的程式碼編輯器

使用自定義帖子型別的區塊模板

如前所述,您可以為自定義帖子型別附加區塊模板。您可以在註冊了自定義帖子型別後再這樣做,但您可能更喜歡在註冊自定義帖子型別時定義區塊模板。

在這種情況下,你可以使用 register_post_type 函式的 template template_lock 引數:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function myplugin_register_book_post_type() {
$args = array(
'label' => esc_html__( 'Books' ),
'labels' => array(
'name' => esc_html__( 'Books' ),
'singular_name' => esc_html__( 'Book' ),
),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_rest' => true,
'rest_namespace' => 'wp/v2',
'has_archive' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'supports' => array( 'title', 'editor', 'thumbnail' ),
'template' => array(
array( 'core/paragraph', array(
'placeholder' => 'Add paragraph...'
) ),
array( 'core/columns',
array(),
array(
array( 'core/column',
array(),
array(
array( 'core/image' )
)
),
array( 'core/column',
array(),
array(
array( 'core/heading', array(
'placeholder' => 'Add H3...',
'level' => 3
) ),
array( 'core/paragraph', array(
'placeholder' => 'Add paragraph...'
) )
)
)
)
)
)
);
register_post_type( 'book', $args );
}
add_action( 'init', 'myplugin_register_book_post_type' );
function myplugin_register_book_post_type() { $args = array( 'label' => esc_html__( 'Books' ), 'labels' => array( 'name' => esc_html__( 'Books' ), 'singular_name' => esc_html__( 'Book' ), ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_rest' => true, 'rest_namespace' => 'wp/v2', 'has_archive' => true, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'supports' => array( 'title', 'editor', 'thumbnail' ), 'template' => array( array( 'core/paragraph', array( 'placeholder' => 'Add paragraph...' ) ), array( 'core/columns', array(), array( array( 'core/column', array(), array( array( 'core/image' ) ) ), array( 'core/column', array(), array( array( 'core/heading', array( 'placeholder' => 'Add H3...', 'level' => 3 ) ), array( 'core/paragraph', array( 'placeholder' => 'Add paragraph...' ) ) ) ) ) ) ) ); register_post_type( 'book', $args ); } add_action( 'init', 'myplugin_register_book_post_type' );
function myplugin_register_book_post_type() {
$args = array(
'label' => esc_html__( 'Books' ),
'labels' => array(
'name' => esc_html__( 'Books' ),
'singular_name' => esc_html__( 'Book' ),
),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_rest' => true,
'rest_namespace' => 'wp/v2',
'has_archive' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'supports' => array( 'title', 'editor', 'thumbnail' ),
'template' => array(
array( 'core/paragraph', array(
'placeholder'	=> 'Add paragraph...'
) ),
array( 'core/columns', 
array(), 
array( 
array( 'core/column',
array(),
array(
array( 'core/image' )
)
), 
array( 'core/column',
array(),
array(
array( 'core/heading', array(
'placeholder'	=> 'Add H3...',
'level'			=> 3
) ),
array( 'core/paragraph', array(
'placeholder'	=> 'Add paragraph...'
) )
) 
)
)
)
)
);
register_post_type( 'book', $args );
}
add_action( 'init', 'myplugin_register_book_post_type' );

就是這樣。下圖顯示了編輯器介面中圖書自定義帖子型別的塊模板。

自定義文章型別的區塊模板

自定義文章型別的區塊模板

完成版面設計後,您可能需要使用圖塊設定來微調區塊模板的行為和外觀。

利用區塊屬性微調區塊模板

我們把區塊模板定義為區塊列表。列表中的每一項都應是一個陣列,包含區塊名稱和可選屬性陣列。如果使用巢狀陣列,可能需要為子區塊新增第三個陣列。

包含欄目區塊的模板可表示如下:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$template = array( 'core/columns',
// attributes
array(),
// nested blocks
array(
array( 'core/column' ),
array( 'core/column' )
)
);
$template = array( 'core/columns', // attributes array(), // nested blocks array( array( 'core/column' ), array( 'core/column' ) ) );
$template = array( 'core/columns', 
// attributes
array(), 
// nested blocks
array(
array( 'core/column' ),
array( 'core/column' ) 
) 
);

如上所述,列表中的第二個陣列是一個可選的區塊屬性陣列。通過這些屬性,您可以自定義模板的外觀,這樣您或您的使用者就可以專注於文章內容,而無需關心頁面佈局和設計。

首先,您可以使用區塊編輯器建立一個區塊結構,作為模板的參考。

區塊編輯器中的區塊佈局

區塊編輯器中的區塊佈局

新增區塊、自定義佈局和樣式,然後切換到程式碼編輯器並查詢區塊分隔符。

欄目區塊的區塊分隔符

欄目區塊的區塊分隔符

區塊分隔符以鍵/值對的形式儲存區塊設定和樣式。您只需從區塊標記中複製並貼上鍵和值,即可填充屬性陣列:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$template = array( 'core/columns',
array(
'verticalAlignment' => 'center',
'align' => 'wide',
'style' => array(
'border' => array(
'width' => '2px',
'radius' => array(
'topLeft' => '12px',
'topRight' => '12px',
'bottomLeft' => '12px',
'bottomRight' => '12px'
)
)
),
'backgroundColor' => 'tertiary'
),
array(
array( 'core/column' ),
array( 'core/column' )
)
);
$template = array( 'core/columns', array( 'verticalAlignment' => 'center', 'align' => 'wide', 'style' => array( 'border' => array( 'width' => '2px', 'radius' => array( 'topLeft' => '12px', 'topRight' => '12px', 'bottomLeft' => '12px', 'bottomRight' => '12px' ) ) ), 'backgroundColor' => 'tertiary' ), array( array( 'core/column' ), array( 'core/column' ) ) );
$template = array( 'core/columns', 
array(
'verticalAlignment'	=> 'center',
'align'				=> 'wide',
'style'				=> array( 
'border'	=> array(
'width'	=> '2px',
'radius'	=> array(
'topLeft'		=> '12px', 
'topRight'		=> '12px', 
'bottomLeft'	=> '12px', 
'bottomRight'	=> '12px'
)
)
),
'backgroundColor' => 'tertiary'
),
array(
array( 'core/column' ),
array( 'core/column' ) 
) 
);

對模板中的每個區塊重複這一過程,就完成了。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$template = array(
array( 'core/paragraph', array(
'placeholder' => 'Add paragraph...'
) ),
array( 'core/columns',
array(
'verticalAlignment' => 'center',
'align' => 'wide',
'style' => array(
'border' => array(
'width' => '2px',
'radius' => array(
'topLeft' => '12px',
'topRight' => '12px',
'bottomLeft' => '12px',
'bottomRight' => '12px'
)
)
),
'backgroundColor' => 'tertiary',
'lock' => array(
'remove' => true,
'move' => true
)
),
array(
array( 'core/column',
array( 'verticalAlignment' => 'center' ),
array(
array( 'core/image',
array(
'style' => array( 'border' => array( 'radius' => '8px' ) )
)
)
)
),
array( 'core/column',
array( 'verticalAlignment' => 'center' ),
array(
array( 'core/heading', array(
'placeholder' => 'Add H3...',
'level' => 3
) ),
array( 'core/paragraph', array(
'placeholder' => 'Add paragraph...'
) )
)
)
)
)
);
$template = array( array( 'core/paragraph', array( 'placeholder' => 'Add paragraph...' ) ), array( 'core/columns', array( 'verticalAlignment' => 'center', 'align' => 'wide', 'style' => array( 'border' => array( 'width' => '2px', 'radius' => array( 'topLeft' => '12px', 'topRight' => '12px', 'bottomLeft' => '12px', 'bottomRight' => '12px' ) ) ), 'backgroundColor' => 'tertiary', 'lock' => array( 'remove' => true, 'move' => true ) ), array( array( 'core/column', array( 'verticalAlignment' => 'center' ), array( array( 'core/image', array( 'style' => array( 'border' => array( 'radius' => '8px' ) ) ) ) ) ), array( 'core/column', array( 'verticalAlignment' => 'center' ), array( array( 'core/heading', array( 'placeholder' => 'Add H3...', 'level' => 3 ) ), array( 'core/paragraph', array( 'placeholder' => 'Add paragraph...' ) ) ) ) ) ) );
$template = array(
array( 'core/paragraph', array(
'placeholder'	=> 'Add paragraph...'
) ),
array( 'core/columns', 
array(
'verticalAlignment'	=> 'center',
'align'				=> 'wide',
'style'				=> array( 
'border'	=> array(
'width'		=> '2px',
'radius'	=> array(
'topLeft'		=> '12px', 
'topRight'		=> '12px', 
'bottomLeft'	=> '12px', 
'bottomRight'	=> '12px'
)
)
),
'backgroundColor' => 'tertiary',
'lock' => array(
'remove'	=> true,
'move'		=> true
)
), 
array( 
array( 'core/column',
array( 'verticalAlignment'	=> 'center' ),
array(
array( 'core/image', 
array(
'style'	=> array( 'border' => array( 'radius' => '8px' ) ) 
) 
)
)
), 
array( 'core/column',
array( 'verticalAlignment'	=> 'center' ),
array(
array( 'core/heading', array(
'placeholder'	=> 'Add H3...',
'level'			=> 3
) ),
array( 'core/paragraph', array(
'placeholder'	=> 'Add paragraph...'
) )
) 
)
)
)
);

鎖定區塊

您可以使用 $post_type_object template_lock 屬性鎖定特定區塊或模板中包含的所有區塊。

當你有一個多作者部落格,並希望防止所有或特定使用者更改區塊模板的佈局時,鎖定模板就會非常有用。

在下面的示例中,我們鎖定了區塊模板中的所有區塊:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function myplugin_register_my_block_template() {
$post_type_object = get_post_type_object( 'post' );
$post_type_object->template = array(
array( 'core/image' ),
array( 'core/heading' ),
array( 'core/paragraph' )
);
$post_type_object->template_lock = 'all';
}
add_action( 'init', 'myplugin_register_my_block_template' );
function myplugin_register_my_block_template() { $post_type_object = get_post_type_object( 'post' ); $post_type_object->template = array( array( 'core/image' ), array( 'core/heading' ), array( 'core/paragraph' ) ); $post_type_object->template_lock = 'all'; } add_action( 'init', 'myplugin_register_my_block_template' );
function myplugin_register_my_block_template() {
$post_type_object = get_post_type_object( 'post' );
$post_type_object->template = array(
array( 'core/image' ),
array( 'core/heading' ),
array( 'core/paragraph' )
);
$post_type_object->template_lock = 'all';
}
add_action( 'init', 'myplugin_register_my_block_template' );

鎖定的區塊會在區塊工具欄和列表檢視中顯示鎖定圖示:

鎖定的標題區塊

鎖定的標題區塊

使用者可以通過圖塊工具欄上的 “選項” 選單解鎖區塊。

解鎖區塊

解鎖區塊

單擊 “解鎖” 後,彈出一個模式視窗,允許您啟用/禁用移動、防止移除或兩者兼而有之:

鎖定選項

鎖定選項

template_lock 可以使用以下值之一:

  • all – 阻止使用者新增新區塊、移動和刪除現有區塊
  • insert – 阻止使用者新增新區塊和刪除現有區塊
  • contentOnly – 使用者只能編輯模板中包含的區塊內容。請注意, contentOnly  只能在模式或模板級別使用,必須用程式碼進行管理。(另請參閱 Locking APIs)。

設定 template_lock,防止模板塊被刪除

設定 template_lock,防止模板塊被刪除

如果要鎖定特定區塊,可以在每個區塊上使用 lock 屬性:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function myplugin_register_my_block_template() {
$post_type_object = get_post_type_object( 'post' );
$post_type_object->template = array(
array( 'core/image' ),
array( 'core/heading' ),
array( 'core/paragraph', array(
'lock' => array(
'remove' => true,
'move' => true
)
) )
);
}
add_action( 'init', 'myplugin_register_my_block_template' );
function myplugin_register_my_block_template() { $post_type_object = get_post_type_object( 'post' ); $post_type_object->template = array( array( 'core/image' ), array( 'core/heading' ), array( 'core/paragraph', array( 'lock' => array( 'remove' => true, 'move' => true ) ) ) ); } add_action( 'init', 'myplugin_register_my_block_template' );
function myplugin_register_my_block_template() {
$post_type_object = get_post_type_object( 'post' );
$post_type_object->template = array(
array( 'core/image' ),
array( 'core/heading' ),
array( 'core/paragraph', array(
'lock' => array(
'remove'	=> true,
'move'		=> true
)
) )
);
}
add_action( 'init', 'myplugin_register_my_block_template' );

lock 屬性可以使用以下值之一:

  • remove: 防止使用者刪除區塊。
  • move: 防止使用者移動區塊。

您還可以將 lock template_lock 結合使用,對塊模板中包含的區塊的行為進行微調。在下面的示例中,我們鎖定了除標題以外的所有區塊:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function myplugin_register_my_block_template() {
$post_type_object = get_post_type_object( 'post' );
$post_type_object->template = array(
array( 'core/image' ),
array( 'core/heading', array(
'lock' => array(
'remove' => false,
'move' => false
)
) ),
array( 'core/paragraph' )
);
$post_type_object->template_lock = 'all';
}
add_action( 'init', 'myplugin_register_my_block_template' );
function myplugin_register_my_block_template() { $post_type_object = get_post_type_object( 'post' ); $post_type_object->template = array( array( 'core/image' ), array( 'core/heading', array( 'lock' => array( 'remove' => false, 'move' => false ) ) ), array( 'core/paragraph' ) ); $post_type_object->template_lock = 'all'; } add_action( 'init', 'myplugin_register_my_block_template' );
function myplugin_register_my_block_template() {
$post_type_object = get_post_type_object( 'post' );
$post_type_object->template = array(
array( 'core/image' ),
array( 'core/heading', array(
'lock' => array(
'remove'	=> false,
'move'		=> false
) 
) ),
array( 'core/paragraph' )
);
$post_type_object->template_lock = 'all';
}
add_action( 'init', 'myplugin_register_my_block_template' );

下圖顯示了已鎖定和未鎖定區塊的區塊模板:

包含鎖定和解鎖區塊的區塊模板

包含鎖定和解鎖區塊的區塊模板

區塊開發者也可以在 attributes 層的區塊定義中使用 lock 屬性(另請參閱單獨區塊鎖定)。

防止使用者解鎖區塊

如果你測試了本文討論的程式碼,你可能已經意識到,你可以從編輯器介面解鎖模板(或其他任何區塊)中包含的區塊。預設情況下,所有有編輯許可權的使用者都可以鎖定或解鎖區塊,這樣做可以繞過模板設定。

你可以使用 block_editor_settings_all 過濾器來控制能否鎖定或解鎖區塊。

該過濾器將向初始化後的編輯器傳送任何設定,這意味著在初始化時用於配置編輯器的任何編輯器設定都可以在傳送前被 PHP WordPress 外掛過濾。

該過濾器的回撥函式需要兩個引數:

  • $settings: 編輯器設定陣列。
  • $context:  WP_Block_Editor_Context  類的一個例項,該物件包含正在渲染的區塊編輯器的相關資訊。

你需要做的就是過濾 $settings['canLockBlocks'] 設定為 true false ,如下例所示:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
add_filter( 'block_editor_settings_all',
function( $settings, $context ) {
if ( $context->post && 'book' === $context->post->post_type ) {
$settings['canLockBlocks'] = false;
}
return $settings;
}, 10, 2
);
add_filter( 'block_editor_settings_all', function( $settings, $context ) { if ( $context->post && 'book' === $context->post->post_type ) { $settings['canLockBlocks'] = false; } return $settings; }, 10, 2 );
add_filter( 'block_editor_settings_all', 
function( $settings, $context ) {
if ( $context->post && 'book' === $context->post->post_type ) {
$settings['canLockBlocks'] = false;
}
return $settings;
}, 10, 2
);

通過對當前使用者功能進行條件檢查,您可以排除特定使用者角色鎖定/解鎖區塊的許可權

在下面的示例中,我們要檢查當前使用者是否可以編輯他人的帖子(換句話說,如果當前使用者的角色是編輯器或更高階別的角色):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
add_filter( 'block_editor_settings_all',
function( $settings, $context ) {
if ( $context->post && 'book' === $context->post->post_type ) {
$settings['canLockBlocks'] = current_user_can( 'edit_others_posts' );
}
return $settings;
}, 10, 2
);
add_filter( 'block_editor_settings_all', function( $settings, $context ) { if ( $context->post && 'book' === $context->post->post_type ) { $settings['canLockBlocks'] = current_user_can( 'edit_others_posts' ); } return $settings; }, 10, 2 );
add_filter( 'block_editor_settings_all', 
function( $settings, $context ) {
if ( $context->post && 'book' === $context->post->post_type ) {
$settings['canLockBlocks'] = current_user_can( 'edit_others_posts' );
}
return $settings;
}, 10, 2
);

下面的圖片比較了管理員和作者的編輯器初始狀態。首先是管理員:

管理員使用者的編輯器初始狀態

管理員使用者的編輯器初始狀態

現在,作者:

作者的編輯器初始狀態

作者的編輯器初始狀態

您還可以檢查當前使用者的任何條件。在下面的示例中,我們要阻止特定使用者鎖定/解鎖區塊:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
add_filter( 'block_editor_settings_all',
function( $settings, $context ) {
$user = wp_get_current_user();
if ( in_array( $user->user_email, [ 'email@example.com' ], true ) ) {
$settings['canLockBlocks'] = false;
}
return $settings;
}, 10, 2
);
add_filter( 'block_editor_settings_all', function( $settings, $context ) { $user = wp_get_current_user(); if ( in_array( $user->user_email, [ 'email@example.com' ], true ) ) { $settings['canLockBlocks'] = false; } return $settings; }, 10, 2 );
add_filter( 'block_editor_settings_all', 
function( $settings, $context ) {
$user = wp_get_current_user();
if ( in_array( $user->user_email, [ 'email@example.com' ], true ) ) {
$settings['canLockBlocks'] = false;
}
return $settings;
}, 10, 2
);

您可以結合更多條件,對誰可以鎖定/解鎖模板中的區塊,誰不可以鎖定/解鎖模板中的區塊進行細化控制。這就是所謂的 “策劃體驗” 的一個方面。

但是,等等。您嘗試過使用程式碼編輯器編輯帖子內容嗎?您可能會驚訝地發現,不允許從使用者介面解鎖區塊的使用者仍然可以通過程式碼編輯器更改內容。

禁用特定使用者角色的程式碼編輯器

預設情況下,所有可以編輯內容的使用者都可以訪問程式碼編輯器。這可能會覆蓋您的鎖定設定,某些使用者可能會破壞或刪除您的模板佈局。

您也可以使用 block_editor_settings_all 過濾 codeEditingEnabled  設定,防止特定使用者角色訪問程式碼編輯器。以下是程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
add_filter( 'block_editor_settings_all',
function( $settings, $context ) {
if ( $context->post && 'book' === $context->post->post_type ) {
$settings['canLockBlocks'] = current_user_can( 'edit_others_posts' );
$settings['codeEditingEnabled'] = current_user_can( 'edit_others_posts' );
}
return $settings;
}, 10, 2
);
add_filter( 'block_editor_settings_all', function( $settings, $context ) { if ( $context->post && 'book' === $context->post->post_type ) { $settings['canLockBlocks'] = current_user_can( 'edit_others_posts' ); $settings['codeEditingEnabled'] = current_user_can( 'edit_others_posts' ); } return $settings; }, 10, 2 );
add_filter( 'block_editor_settings_all', 
function( $settings, $context ) {
if ( $context->post && 'book' === $context->post->post_type ) {
$settings['canLockBlocks'] = current_user_can( 'edit_others_posts' );
$settings['codeEditingEnabled'] = current_user_can( 'edit_others_posts' );
}
return $settings;
}, 10, 2
);

有了這段程式碼,沒有 edit_others_posts 功能的使用者將無法訪問程式碼編輯器。下圖顯示了作者的選項工具欄。

無法訪問程式碼編輯器的使用者角色的選項工具欄

無法訪問程式碼編輯器的使用者角色的選項工具欄

這就是通過 PHP 構建區塊模板所需的知識。現在,如果你是一名 Gutenberg 區塊開發人員,並且喜歡使用 JavaScript,那麼你可能更願意選擇另一種方法。

如何使用 JavaScript 建立模板

如果您決定使用 JavaScript,為文章新增區塊模板的工作方式就不同了。你仍然可以建立一個模板,但需要建立一個自定義區塊,並使用 InnerBlocks 元件,這在我們的古騰堡區塊開發指南中已有討論。

InnerBlocks 輸出了一對元件,可用於區塊實現,以啟用巢狀區塊內容。– Source: InnerBlocks

如何使用?

您可以在自定義區塊中使用 InnerBlocks ,使用方法與其他 Gutenberg 元件相同。

首先,您需要將它與其他依賴項一起從軟體包中包含進來:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import { registerBlockType } from '@wordpress/blocks';
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';
import { registerBlockType } from '@wordpress/blocks'; import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';
import { registerBlockType } from '@wordpress/blocks';
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';

接下來,你將定義 InnerBlocks 屬性。在下面的示例中,我們將宣告一個 TEMPLATE 常量,然後用它來設定 InnerBlocks 元素的 template 屬性值:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const TEMPLATE = [
[ 'core/paragraph', { 'placeholder': 'Add paragraph...' } ],
[ 'core/columns', { verticalAlignment: 'center' },
[
[
'core/column',
{ templateLock: 'all' },
[
[ 'core/image' ]
]
],
[
'core/column',
{ templateLock: 'all' },
[
[
'core/heading',
{'placeholder': 'Add H3...', 'level': 3}
],
[
'core/paragraph',
{'placeholder': 'Add paragraph...'}
]
],
]
]
]
];
registerBlockType( metadata.name, {
title: 'My Template',
category: 'widgets',
edit: ( props ) => {
return(
<div>
<InnerBlocks
template={ TEMPLATE }
templateLock="insert"
/>
</div>
)
},
save() {
const blockProps = useBlockProps.save();
return(
<div { ...blockProps }>
<InnerBlocks.Content />
</div>
)
}
} );
const TEMPLATE = [ [ 'core/paragraph', { 'placeholder': 'Add paragraph...' } ], [ 'core/columns', { verticalAlignment: 'center' }, [ [ 'core/column', { templateLock: 'all' }, [ [ 'core/image' ] ] ], [ 'core/column', { templateLock: 'all' }, [ [ 'core/heading', {'placeholder': 'Add H3...', 'level': 3} ], [ 'core/paragraph', {'placeholder': 'Add paragraph...'} ] ], ] ] ] ]; registerBlockType( metadata.name, { title: 'My Template', category: 'widgets', edit: ( props ) => { return( <div> <InnerBlocks template={ TEMPLATE } templateLock="insert" /> </div> ) }, save() { const blockProps = useBlockProps.save(); return( <div { ...blockProps }> <InnerBlocks.Content /> </div> ) } } );
const TEMPLATE = [
[ 'core/paragraph', { 'placeholder': 'Add paragraph...' } ],
[ 'core/columns', { verticalAlignment: 'center' }, 
[
[ 
'core/column', 
{ templateLock: 'all' }, 
[
[ 'core/image' ]
]
],
[ 
'core/column', 
{ templateLock: 'all' }, 
[
[ 
'core/heading', 
{'placeholder': 'Add H3...', 'level': 3}
], 
[ 
'core/paragraph', 
{'placeholder': 'Add paragraph...'} 
]
], 
]
]
]
];
registerBlockType( metadata.name, {
title: 'My Template',
category: 'widgets',
edit: ( props ) => {
return(
<div>
<InnerBlocks
template={ TEMPLATE }
templateLock="insert"
/>
</div>
)
},
save() {
const blockProps = useBlockProps.save();
return(
<div { ...blockProps }>
<InnerBlocks.Content />
</div>
)
}
} );

這段程式碼非常簡單。你應該注意到,我們使用了兩次 templateLock 屬性,首先是在塊級別,然後是在 InnerBlocks 元素內部。有關可用道具的完整列表,請參閱 InnerBlocks 參考資料和《區塊編輯器手冊》。

現在自己試試吧。

首先,使用本地開發環境建立一個本地 WordPress 安裝。

然後,啟動命令列工具,導航到 plugins 資料夾,並執行以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx @wordpress/create-block template-block
npx @wordpress/create-block template-block
npx @wordpress/create-block template-block

你可以隨意更改區塊的名稱。如果你想控制啟動區塊的方方面面,只需遵循我們的區塊開發權威指南中提供的說明即可。

安裝完成後,執行以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
cd template-block
npm start
cd template-block npm start
cd template-block
npm start

啟動 WordPress 管理儀表盤並導航至外掛螢幕。找到並啟用 Template Block 外掛。

在您最喜歡的程式碼編輯器中,開啟 src 資料夾下的 index.js 檔案。複製並貼上上面的程式碼,儲存 index.js,然後回到 WordPress 面板,建立一個新的帖子或頁面。

開啟區塊插入器,向下滾動到 “小工具” 部分。在那裡,你應該能找到你的自定義區塊。

區塊插入器中的自定義區塊

區塊插入器中的自定義區塊

將其新增到帖子中,自定義內容,然後儲存帖子。

自定義模板的列表檢視

自定義模板的列表檢視

如果切換到程式碼編輯器,你會看到以下標記:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!-- wp:create-block/template-block -->
<div class="wp-block-create-block-template-block"><!-- wp:paragraph {"placeholder":"Add paragraph..."} -->
<p></p>
<!-- /wp:paragraph -->
<!-- wp:columns {"verticalAlignment":"center"} -->
<div class="wp-block-columns are-vertically-aligned-center"><!-- wp:column {"templateLock":"all"} -->
<div class="wp-block-column"><!-- wp:image -->
<figure class="wp-block-image"><img alt=""/></figure>
<!-- /wp:image --></div>
<!-- /wp:column -->
<!-- wp:column {"templateLock":"all"} -->
<div class="wp-block-column"><!-- wp:heading {"level":3,"placeholder":"Add H3..."} -->
<h3 class="wp-block-heading"></h3>
<!-- /wp:heading -->
<!-- wp:paragraph {"placeholder":"Add paragraph..."} -->
<p></p>
<!-- /wp:paragraph --></div>
<!-- /wp:column --></div>
<!-- /wp:columns --></div>
<!-- /wp:create-block/template-block -->
<!-- wp:create-block/template-block --> <div class="wp-block-create-block-template-block"><!-- wp:paragraph {"placeholder":"Add paragraph..."} --> <p></p> <!-- /wp:paragraph --> <!-- wp:columns {"verticalAlignment":"center"} --> <div class="wp-block-columns are-vertically-aligned-center"><!-- wp:column {"templateLock":"all"} --> <div class="wp-block-column"><!-- wp:image --> <figure class="wp-block-image"><img alt=""/></figure> <!-- /wp:image --></div> <!-- /wp:column --> <!-- wp:column {"templateLock":"all"} --> <div class="wp-block-column"><!-- wp:heading {"level":3,"placeholder":"Add H3..."} --> <h3 class="wp-block-heading"></h3> <!-- /wp:heading --> <!-- wp:paragraph {"placeholder":"Add paragraph..."} --> <p></p> <!-- /wp:paragraph --></div> <!-- /wp:column --></div> <!-- /wp:columns --></div> <!-- /wp:create-block/template-block -->
<!-- wp:create-block/template-block -->
<div class="wp-block-create-block-template-block"><!-- wp:paragraph {"placeholder":"Add paragraph..."} -->
<p></p>
<!-- /wp:paragraph -->
<!-- wp:columns {"verticalAlignment":"center"} -->
<div class="wp-block-columns are-vertically-aligned-center"><!-- wp:column {"templateLock":"all"} -->
<div class="wp-block-column"><!-- wp:image -->
<figure class="wp-block-image"><img alt=""/></figure>
<!-- /wp:image --></div>
<!-- /wp:column -->
<!-- wp:column {"templateLock":"all"} -->
<div class="wp-block-column"><!-- wp:heading {"level":3,"placeholder":"Add H3..."} -->
<h3 class="wp-block-heading"></h3>
<!-- /wp:heading -->
<!-- wp:paragraph {"placeholder":"Add paragraph..."} -->
<p></p>
<!-- /wp:paragraph --></div>
<!-- /wp:column --></div>
<!-- /wp:columns --></div>
<!-- /wp:create-block/template-block -->

現在,請在您最喜歡的瀏覽器中預覽效果。如果需要改進區塊外觀,只需更改 style.scss 檔案中的樣式即可。

一旦對定製感到滿意,請停止程序並執行 npm run build 。專案的所有檔案都將被壓縮,並在新的 build 資料夾中供生產使用。

簡單而強大,不是嗎?

現在,你只需點選幾下,就能建立高階的區塊模板,並將其包含在內容中。

小結

在文章或自定義文章型別中新增塊模板可以大大加快和改善 WordPress 網站的建立和編輯體驗。區塊模板在多使用者網站上尤其有用,在這種網站上,多個使用者都可以建立內容,而您需要他們遵守相同的格式。

這還可以讓您建立統一的佈局,而不必在每次建立新文章時手動新增塊模式。想想評論或食譜網站,每個頁面都應遵守相同的結構。

將您在建立靜態動態自定義區塊、區塊樣板和區塊模板方面獲得的知識結合起來,您就能始終為建立任何型別的 WordPress 網站找到最高效、最有效的解決方案。

現在就看你的了。您是否已經探索過區塊模板?你覺得它們最適合用於哪種情況?請在下面的評論中分享您的經驗。

評論留言