WordPressのクエリループブロックの投稿見出しやサイトタイトルブロックをpでレンダリングする

WordPressのテンプレートブロックは投稿見出しやサイトタイトルのタグが<h1>~<h6>でレンダリングされるが、ページによっては見出しを使用したくないことがある。その場合はブロックバリエーションを作成して<p>でレンダリングすることができる。

クエリループブロックの投稿見出しを<p>でレンダリングする(失敗!)

この方法はクエリループブロックに不整合を起こすため失敗。

投稿見出し(data-type=”core/post-title”)のコードは次のようになっている。

<h2 class="wp-block-post-title">サンプル</h2>

見出しレベルの変更は可能だが、クエリループでは見出しにしたくない。その場合はブロックバリエーションを作成する。

add_filter(
    'get_block_type_variations',
    function($variations, $block_type) {

        if ('core/post-title' !== $block_type->name) {
            return $variations;
        }

        $variations[] = array(
            'name'  => 'post-title-text',
            'title' => 'Post Title Text',

            'attributes' => array(
                'level' => 0,
            ),

            'isActive' => array(
                'level',
            ),
        );

        return $variations;
    },
    10,
    2
);

ポイントは下記

            'attributes' => array(
                'level' => 0,
            ),

WordPressでは見出しレベルを0にすると段落ブロックとしてレンダリングされる。その結果、<p>に変換される。

<p class="wp-block-post-title">サンプル</p>

サイトタイトルブロックを<p>でレンダリングする

add_filter(
    'get_block_type_variations',
    function($variations, $block_type) {

        if ('core/site-title' !== $block_type->name) {
            return $variations;
        }

        $variations[] = array(
            'name'  => 'site-title-paragraph',
            'title' => 'Site Title Paragraph',

            'attributes' => array(
                'level' => 0,
            ),

            'isActive' => array(
                'level',
            ),
        );

        return $variations;
    },
    10,
    2
);

比較するとタグが変更になっている

// デフォルト
<h1 class="wp-block-site-title">
  <a href="https://example.com" target="_self" rel="home">Example</a>
</h1>

// 段落に変更
<p class="wp-block-site-title">
  <a href="https://hgroup.local" target="_self" rel="home">Example</a>
</p>