WP_HTML_Tag_Processorの練習として、Topページのサイトタイトルのtarget属性を削除します。
コンテンツ
変更前のHTMLコード
サイトタイトルブロックは2箇所にあります。
<!-- ヘッダー -->
<p class="wp-block-site-title"><a href="http://bdev.com" target="_self" rel="home" aria-current="page">bdev</a></p>
<!-- フッター -->
<h2 class="wp-block-site-title"><a href="http://bdev.com" target="_self" rel="home" aria-current="page">bdev</a></h2>
サイトタイトルブロックのtarget属性をすべて削除する場合
ページ内に挿入されたサイトタイトルブロックの<a>のtarget属性をすべて削除します。
<?php
/****************************
Topページのサイトタイトルの target を削除
*****************************/
function my_delete_sitetitle_attribute($block_content, $block) {
// トップページ以外ではそのまま返す
if (! is_front_page()) {
return $block_content;
}
// 対象ブロックが "core/site-title" である場合のみ処理
if ('core/site-title' !== $block['blockName']) {
return $block_content;
}
$processor = new WP_HTML_Tag_Processor($block_content);
// 最初の<a>を探す
if ($processor->next_tag('a')) {
$processor->remove_attribute('target');
}
return $processor->get_updated_html();
}
add_filter('render_block_core/site-title', 'my_delete_sitetitle_attribute', 10, 2);
ヘッダーにあるサイトタイトルブロックのみ対象とする場合
ヘッダーの場合は<p>から始まるため、<p>タグから始まっていない場合、何もしないでそのまま返すという条件分岐に追加する。
if (strpos($block_content, '<p class="wp-block-site-title"') !== 0) {
return $block_content;
}
strpos($block_content, ‘<p class=”wp-block-site-title”‘)
ある文字列の中に特定の文字列が現れる位置(インデックス)を返す
この場合、$block_content の中に <p class=”wp-block-site-title” が含まれているかを調べている
strpos() が 0 を返すとき → その文字列が先頭(インデックス0)にある
!== 0の場合、「先頭以外にある、または存在しない」という意味
Topページのサイトタイトルの target=”_self” を削除
next_tag(‘p’)で書き換え対象を限定してtarget=”_self”のみ削除します。
function my_change_only_p_tag_sitetitle($block_content, $block) {
if (! is_front_page()) {
return $block_content;
}
if ('core/site-title' !== $block['blockName']) {
return $block_content;
}
// WP_HTML_Tag_Processorで処理
$processor = new WP_HTML_Tag_Processor($block_content);
// <p> タグを最初に見つける
if ($processor->next_tag('p')) {
// 最初の <a> タグに対して処理
if ($processor->next_tag('a')) {
// target="_self" を削除
if ($processor->get_attribute('target') === '_self') {
$processor->remove_attribute('target');
}
}
}
return $processor->get_updated_html();
}
add_filter('render_block_core/site-title', 'my_change_only_p_tag_sitetitle', 10, 2);
core/site-titleで書き換え対象を限定して削除します。
<?php
/****************************
Topページのサイトタイトルの target="_self" を削除
*****************************/
function my_delete_sitetitle_self_attribute($block_content, $block) {
// トップページ以外ではそのまま返す
if (! is_front_page()) {
return $block_content;
}
// 対象ブロックが "core/site-title" である場合のみ処理
if ('core/site-title' !== $block['blockName']) {
return $block_content;
}
if (strpos($block_content, '<p class="wp-block-site-title"') !== 0) {
return $block_content;
}
$processor = new WP_HTML_Tag_Processor($block_content);
// 最初の<a>を探す
if ($processor->next_tag('a')) {
if ($processor->get_attribute('target') === '_self') {
$processor->remove_attribute('target');
}
}
return $processor->get_updated_html();
}
add_filter('render_block_core/site-title', 'my_delete_sitetitle_self_attribute', 10, 2);