概要
get_default_block_categories
フィルタは、デフォルトのブロックタイプのカテゴリーを取得する際に使用されます。このフィルタを使用することで、新たなカテゴリーを追加したり、既存のカテゴリーを変更したりすることができます。以下は、このフィルタがよく使われる機能の例です。
- ブロックエディタのユーザー体験を向上させるためのカスタムカテゴリーの追加
- 特定のプラグインに必要なカテゴリーを追加するためのカスタマイズ
- テーマ固有のブロックカテゴリーを追加するための調整
- 不要なデフォルトカテゴリーを削除することによる整理
- 設定に応じた条件付きでカテゴリーの表示を変更
- 企業やブランドに特化したカテゴリーを追加
- ユーザーのニーズに応じたカスタムフィルタリングを行う
- デザインや機能の変更に伴うブロックカテゴリーの更新
構文
function my_custom_block_categories( $categories ) {
// カスタムカテゴリーを追加
return $categories;
}
add_filter( 'get_default_block_categories', 'my_custom_block_categories' );
パラメータ
$categories
: デフォルトのブロックカテゴリーの配列。
戻り値
- 更新されたブロックカテゴリーの配列。
関連する関数
https://refwp.com/?titleonly=1&s=get_default_block_categories
使用可能なバージョン
- WordPress 5.0以降
コアファイルのパス
wp-includes/blocks.php
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
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 |
サンプルコード
-
カスタムカテゴリーを追加する
function my_custom_block_categories( $categories ) { $categories[] = array( 'slug' => 'my-category', 'title' => __( 'My Custom Category', 'text-domain' ), 'icon' => 'star', ); return $categories; } add_filter( 'get_default_block_categories', 'my_custom_block_categories' );
このコードは、自作の「My Custom Category」というカテゴリーを追加します。
-
デフォルトカテゴリーを削除する
function remove_default_categories( $categories ) { foreach ( $categories as $key => $category ) { if ( $category['slug'] === 'text' ) { unset( $categories[$key] ); } } return array_values( $categories ); } add_filter( 'get_default_block_categories', 'remove_default_categories' );
このコードでは、デフォルトの「text」カテゴリーを削除します。
-
条件付きでカテゴリーを変更する
function conditional_block_categories( $categories ) { if ( current_user_can( 'editor' ) ) { $categories[] = array( 'slug' => 'editor-category', 'title' => __( 'Editor Category', 'text-domain' ), ); } return $categories; } add_filter( 'get_default_block_categories', 'conditional_block_categories' );
ここでは、エディター権限を持つユーザーにのみ「Editor Category」を表示するようにしています。
-
複数のカスタムカテゴリーを追加する
function multiple_custom_categories( $categories ) { $new_categories = array( array('slug' => 'design', 'title' => __( 'Design', 'text-domain' )), array('slug' => 'development', 'title' => __( 'Development', 'text-domain' )), ); return array_merge( $categories, $new_categories ); } add_filter( 'get_default_block_categories', 'multiple_custom_categories' );
こちらのコードは「Design」と「Development」の2つのカテゴリーを追加します。
-
カテゴリー名を翻訳する
function translate_block_categories( $categories ) { foreach ( $categories as &$category ) { $category['title'] = __( $category['title'], 'text-domain' ); } return $categories; } add_filter( 'get_default_block_categories', 'translate_block_categories' );
このコードは、追加されたカテゴリーのタイトルを翻訳可能にします。
引用元: すべてのサンプルコードは、カスタムブロックカテゴリーの管理に関する一般的なWordPressのドキュメントに基づいています。