wp_get_post_content_block_attributes()


WordPressのwp_get_post_content_block_attributes()関数は、指定された投稿のコンテンツブロックの属性を取得するために使用されます。この関数は、ブロックエディター(Gutenberg)で作成された投稿のブロック属性を取得する際に役立ちます。

構文

wp_get_post_content_block_attributes( int $post_id, string $block_name );

引数の説明:

  • $post_id (int) — 属性を取得したい投稿のID。
  • $block_name (string) — 属性を取得したいブロックの名前。

例1: 投稿のブロック属性を取得

この例では、指定された投稿の特定のブロックの属性を取得します。

$attributes = wp_get_post_content_block_attributes( get_the_ID(), 'core/paragraph' );

例2: ブロック属性を表示

取得したブロック属性を表示します。

$attributes = wp_get_post_content_block_attributes( get_the_ID(), 'core/image' ); print_r( $attributes );

例3: 特定の属性値を取得

ブロックの特定の属性値を取得します。

$attributes = wp_get_post_content_block_attributes( get_the_ID(), 'core/heading' ); echo $attributes['content'];

例4: ブロック属性が存在するか確認

ブロック属性が存在するかどうかを確認します。

$attributes = wp_get_post_content_block_attributes( get_the_ID(), 'core/list' ); if ( ! empty( $attributes ) ) { echo '属性が存在します。'; }

例5: ブロック属性を配列として取得

ブロック属性を配列として取得し、その内容を確認します。

$attributes = wp_get_post_content_block_attributes( get_the_ID(), 'core/quote' ); var_dump( $attributes );

例6: ブロック属性をJSON形式で出力

ブロック属性をJSON形式で出力します。

$attributes = wp_get_post_content_block_attributes( get_the_ID(), 'core/gallery' ); echo json_encode( $attributes );

例7: ブロック属性を条件付きで処理

ブロック属性に基づいて条件付きで処理を行います。

$attributes = wp_get_post_content_block_attributes( get_the_ID(), 'core/cover' ); if ( isset( $attributes['url'] ) ) { echo 'カバー画像のURL: ' . $attributes['url']; }

注意点

  • この関数は、ブロックエディター(Gutenberg)を使用している場合にのみ有効です。
  • 指定されたブロックが投稿に存在しない場合、関数は空の配列を返します。
  • 投稿IDが無効な場合、関数はfalseを返します。

関連機能: