Last active
July 3, 2023 18:28
-
-
Save mopeneko/c1de0639eaaa8e03f1d8cd785930e821 to your computer and use it in GitHub Desktop.
[THE THOR] h2 のn番目以降に広告コードを挿入する m個飛ばし
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// h2 のn番目以降に広告コードを挿入する | |
// m個飛ばし | |
function insert_adcode($the_content) { | |
$n = 2; | |
$m = 1; | |
// 固定ページではそのまま表示 | |
if (!is_single()) { | |
return $the_content; | |
} | |
$has_h2 = preg_match_all('/^<h2.*?>.+?<\/h2>$/im', $the_content, $h2_list, PREG_SET_ORDER); | |
// h2タグが無ければそのまま表示 | |
if (!$has_h2) { | |
return $the_content; | |
} | |
// h2タグがnつ以下ならそのまま表示 | |
if (count($h2_list) <= $n) { | |
return $the_content; | |
} | |
// nつ目以降のh2タグのみを切り出し | |
$h2_list = array_slice($h2_list, $n-1); | |
foreach ($h2_list as $idx => $h2) { | |
// m個飛ばし | |
if (($idx+1) % ($m+1) == 0) { | |
continue; | |
} | |
$the_content = str_replace($h2[0], '[adcode]' . $h2[0], $the_content); | |
} | |
return $the_content; | |
} | |
add_filter('the_content', 'insert_adcode'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment