register_block_core_post_terms()


WordPressのregister_block_core_post_terms()関数は、投稿に関連付けられたターム(カテゴリーやタグなど)を表示するためのブロックを登録するために使用されます。この関数は、ブロックエディター内でターム情報を簡単に表示するための機能を提供します。

構文

register_block_core_post_terms( array $args );

引数の説明:

  • $args(array) — ブロックの設定を定義するための配列。以下のキーを持つことができます:
    • 'name'(string) — ブロックの名前。
    • 'title'(string) — ブロックのタイトル。
    • 'description'(string) — ブロックの説明。
    • 'render_callback'(callable) — ブロックのレンダリングを行うコールバック関数。
    • 'category'(string) — ブロックのカテゴリー。

例1: 基本的なブロックの登録

この例では、投稿のタームを表示するためのシンプルなブロックを登録します。

register_block_core_post_terms( array( 'name' => 'core/post-terms', 'title' => '投稿ターム', 'description' => '投稿に関連付けられたタームを表示します。', 'render_callback' => 'render_post_terms_block', 'category' => 'widgets' ) );

例2: カスタムレンダリング関数の使用

カスタムレンダリング関数を使用して、ターム情報を表示する方法です。

function render_post_terms_block( $attributes ) { return get_the_term_list( get_the_ID(), 'category', 'カテゴリー: ', ', ', '' ); } register_block_core_post_terms( array( 'name' => 'core/post-terms', 'title' => 'カスタム投稿ターム', 'render_callback' => 'render_post_terms_block' ) );

例3: タグ情報を表示するブロック

タグ情報を表示するためのブロックを登録します。

register_block_core_post_terms( array( 'name' => 'core/post-tags', 'title' => '投稿タグ', 'description' => '投稿に関連付けられたタグを表示します。', 'render_callback' => function() { return get_the_tag_list( 'タグ: ', ', ', '' ); }, 'category' => 'widgets' ) );

例4: カスタムタクソノミーのタームを表示

カスタムタクソノミーのタームを表示するブロックを登録します。

register_block_core_post_terms( array( 'name' => 'core/custom-terms', 'title' => 'カスタムターム', 'render_callback' => function() { return get_the_term_list( get_the_ID(), 'custom_taxonomy', 'カスタムターム: ', ', ', '' ); } ) );

例5: ターム情報をリスト形式で表示

ターム情報をリスト形式で表示するブロックを登録します。

register_block_core_post_terms( array( 'name' => 'core/term-list', 'title' => 'タームリスト', 'render_callback' => function() { $terms = get_the_terms( get_the_ID(), 'category' ); if ( $terms && ! is_wp_error( $terms ) ) { $term_list = '<ul>'; foreach ( $terms as $term ) { $term_list .= '<li>' . esc_html( $term->name ) . '</li>'; } $term_list .= '</ul>'; return $term_list; } return ''; } ) );

例6: ターム情報をカンマ区切りで表示

ターム情報をカンマ区切りで表示するブロックを登録します。

register_block_core_post_terms( array( 'name' => 'core/term-comma', 'title' => 'タームカンマ区切り', 'render_callback' => function() { return get_the_term_list( get_the_ID(), 'post_tag', '', ', ', '' ); } ) );

例7: ターム情報をカスタムスタイルで表示

ターム情報をカスタムスタイルで表示するブロックを登録します。

register_block_core_post_terms( array( 'name' => 'core/term-styled', 'title' => 'スタイル付きターム', 'render_callback' => function() { $terms = get_the_terms( get_the_ID(), 'category' ); if ( $terms && ! is_wp_error( $terms ) ) { $output = '<div style="background-color: #f0f0f0; padding: 10px;">'; foreach ( $terms as $term ) { $output .= '<span style="color: blue;">' . esc_html( $term->name ) . '</span> '; } $output .= '</div>'; return $output; } return ''; } ) );

注意点

  • この関数は、ブロックエディターが有効な場合にのみ動作します。
  • カスタムレンダリング関数を使用する場合、適切なエスケープ処理を行ってください。
  • ターム情報が存在しない場合、空の文字列を返すようにしてください。

関連機能: