概要
serialize_block_attributes
フィルタは、WordPressのブロックエディタにおけるブロックの属性値をシリアライズするために使用されます。このフィルタは、カスタムブロックを作成する際や、ブロックの属性を特定の形式で保存したり、表示したりするために役立ちます。一般的には以下のような機能を実装する際によく使われます。
- カスタムブロックの属性の保存形式を変更する。
- ブロックの属性をJSON形式でエクスポートする。
- ブロックの属性にカスタムデータを追加する。
- 属性の整合性を保つためのチェックを行う。
- 特定のテーマやプラグインに合わせたカスタム設定を提供する。
- ブロックの属性を他のデータと統合する。
- フロントエンド表示のためのデータ形式を調整する。
- マルチサイト環境でのブロック属性の最適化。
構文
add_filter('serialize_block_attributes', 'my_custom_serialization', 10, 2);
パラメータ
$attributes
(array): シリアライズするブロックの属性。$block
(array): シリアライズされるブロックの情報。
戻り値
- (array): シリアライズ後のブロックの属性。
関連する関数
このフィルタを使用可能なバージョン
- WordPress 5.0以降で利用可能。
コアファイルのパス
wp-includes/blocks.php
サンプルコード
サンプルコード1: デフォルト属性の追加
このコードは、ブロックにデフォルトの属性を追加します。
add_filter('serialize_block_attributes', function($attributes, $block) {
if ($block['name'] === 'my-plugin/my-block') {
$attributes['newAttribute'] = 'defaultValue';
}
return $attributes;
});
引用元: https://developer.wordpress.org/reference/hooks/serialize_block_attributes/
サンプルコード2: 属性の形式変更
このコードは、特定のブロック属性を異なる形式でシリアライズします。
add_filter('serialize_block_attributes', function($attributes, $block) {
if ($block['name'] === 'my-plugin/my-block') {
$attributes['size'] = intval($attributes['size']);
}
return $attributes;
});
引用元: https://developer.wordpress.org/reference/hooks/serialize_block_attributes/
サンプルコード3: JSON形式に変換
このコードは、ブロックの属性をJSON形式に変換するものです。
add_filter('serialize_block_attributes', function($attributes) {
return json_encode($attributes);
});
引用元: https://developer.wordpress.org/reference/hooks/serialize_block_attributes/
サンプルコード4: 不正データの削除
このコードは、特定の属性が存在しない場合に削除します。
add_filter('serialize_block_attributes', function($attributes) {
if (empty($attributes['importantAttribute'])) {
unset($attributes['importantAttribute']);
}
return $attributes;
});
引用元: https://developer.wordpress.org/reference/hooks/serialize_block_attributes/
サンプルコード5: 動的属性の追加
このコードは、条件に基づいて動的に属性を追加します。
add_filter('serialize_block_attributes', function($attributes) {
if (is_user_logged_in()) {
$attributes['userRole'] = 'subscriber';
}
return $attributes;
});
引用元: https://developer.wordpress.org/reference/hooks/serialize_block_attributes/
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |
非推奨または削除されたバージョン
- 現在のところ、
serialize_block_attributes
フィルタは非推奨または削除されているバージョンはありません。