LoginSignup
0
0

More than 1 year has passed since last update.

Wordpressの記事の見出しを正規化する

Posted at

見出しってよくわかってない?

なんとなく、昔からある とか

とりあえず、<h1>が最初の見出しだな、とか
CMSで書いているとおかしくなるので、
正規化できるようにしました。

この記事も、わざと見出しがわかってないフリして記述しています。

対象

  • HTMLの見出しの仕組みをよくわかってない社員や記事執筆者がいる方へ
  • 自作テーマを使用中

最適化をする

ここにおいては、最大の見出しレベルは <h3> と仮定して
<h1> もしくは <h2> レベルのを強制的に <h3> にして
それ以下のレベルの見出しも適切に置換する非常に単純な記述です

ここでは、サイトのタイトルを <h1>、記事のタイトルを <h2> で既に使用してしまってる場合を想定しています。

single.php
<?php
	$wpcontent = apply_filters( 'the_content', get_the_content() );
	$wpcontent = str_replace( ']]>', ']]&gt;', $wpcontent );

	// 見出しを h3以下に正規化する
	$hh=0;
	if(strpos($wpcontent, '<h2') !== false) {
		$hh=2;
	}
	if(strpos($wpcontent, '<h1') !== false) {
		$hh=1;
	}
	$hharray=array();
	if($hh==1) {
		$wpcontent = str_replace(
			['<h5','</h5','<h4','</h4','<h3','</h3','<h2','</h2','<h1','</h1'],
			['<h6','</h6','<h6','</h6','<h5','</h5','<h4','</h4','<h3','</h3'],
			$wpcontent);
	}
	if($hh==2) {
		$wpcontent = str_replace(
			['<h5','</h5','<h4','</h4','<h3','</h3','<h2','</h2'],
			['<h6','</h6','<h5','</h5','<h4','</h4','<h3','</h3'],
			$wpcontent);
	}

	echo $wpcontent;
?>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0