register_block_style_handle()


WordPressのregister_block_style_handle()関数は、ブロックスタイルのハンドルを登録するために使用されます。スタイルの依存関係やバージョンを管理し、ブロックエディターやフロントエンドで正しく読み込まれるようにします。

構文

register_block_style_handle( string $handle, string $block_name, string $path, array $deps = array(), string $version = null, string $media = 'all' );

引数の説明:

  • $handle (string) — 登録するスタイルのハンドル名
  • $block_name (string) — 対象ブロックの名前(例: ‘core/paragraph’)
  • $path (string) — CSSファイルのパス(相対または絶対)
  • $deps (array) — 依存するスタイルハンドルの配列
  • $version (string) — スタイルのバージョン(省略可能)
  • $media (string) — メディアクエリ(デフォルト: ‘all’)

例1: 基本的なブロックスタイルの登録

段落ブロックにカスタムスタイルを追加します。

register_block_style_handle( 'my-paragraph-style', 'core/paragraph', get_template_directory_uri() . '/styles/paragraph.css' );

例2: 依存関係のあるスタイルの登録

既存のスタイルに依存するカスタムスタイルを登録します。

register_block_style_handle( 'my-button-style', 'core/button', get_stylesheet_directory_uri() . '/css/button.css', array( 'wp-block-button' ) );

例3: バージョン指定付きのスタイル登録

バージョン番号を指定してスタイルを登録します。

register_block_style_handle( 'my-heading-style', 'core/heading', get_theme_file_uri( 'assets/css/heading.css' ), array(), '1.0.0' );

例4: メディアクエリを指定したスタイル

印刷用のスタイルを別途登録します。

register_block_style_handle( 'my-print-style', 'core/image', get_template_directory_uri() . '/print.css', array(), null, 'print' );

例5: 子テーマでのスタイル登録

子テーマから親テーマのスタイルを上書きします。

register_block_style_handle( 'child-theme-style', 'core/list', get_stylesheet_directory_uri() . '/override-list.css', array( 'parent-theme-list' ) );

例6: 複数ブロックに同じスタイルを適用

複数のブロックに同じスタイルを登録します。

foreach( array( 'core/paragraph', 'core/heading' ) as $block ) { register_block_style_handle( 'shared-style', $block, get_template_directory_uri() . '/shared.css' ); }

例7: 条件付きでスタイルを登録

特定の条件下でのみスタイルを登録します。

if( is_page_template( 'special.php' ) ) { register_block_style_handle( 'special-style', 'core/group', get_template_directory_uri() . '/special.css' ); }

注意点:

  • スタイルハンドル名は一意である必要があります
  • CSSファイルのパスが正しいことを確認してください
  • フックのタイミングに注意(wp_enqueue_scriptsなど)

関連機能: