get_block_categories()


WordPressの関数get_block_categories()は、ブロックエディタで使用可能なブロックカテゴリーのリストを取得します。

構文

get_block_categories( WP_Post $post );
  • $post (WP_Post) — ブロックカテゴリーを取得する対象の投稿オブジェクト。

例1: 現在の投稿のブロックカテゴリーを取得

現在表示されている投稿のブロックカテゴリーを取得します。

$categories = get_block_categories( get_post() );

例2: 特定の投稿IDのブロックカテゴリーを取得

指定した投稿IDのブロックカテゴリーを取得します。

$categories = get_block_categories( get_post( 123 ) );

例3: カテゴリー名をループで表示

取得したブロックカテゴリーの名前をループで表示します。

foreach( get_block_categories( get_post() ) as $category ) { echo $category['title']; }

例4: カスタム投稿タイプのブロックカテゴリー取得

カスタム投稿タイプのブロックカテゴリーを取得します。

$post = get_posts( array( 'post_type' => 'custom_post' ) )[0]; $categories = get_block_categories( $post );

例5: JSON形式でブロックカテゴリーを出力

取得したブロックカテゴリーをJSON形式で出力します。

echo json_encode( get_block_categories( get_post() ) );

例6: カテゴリーのスラッグを取得

ブロックカテゴリーのスラッグを取得します。

$slugs = array_column( get_block_categories( get_post() ), 'slug' );

例7: フィルターフックでカテゴリーを変更

block_categoriesフィルターフックを使用してカテゴリーを変更します。

add_filter( 'block_categories', function( $categories, $post ) { return array_merge( $categories, [['slug' => 'custom', 'title' => 'Custom Category']] ); }, 10, 2 );

注意点:

  • この関数はブロックエディタ(Gutenberg)が有効な場合のみ動作します。
  • 返されるカテゴリーはデフォルトとカスタムの両方を含みます。

関連機能: