SWELLの記事中のh2上にアドセンス広告を入れ込むカスタマイズは、Cocoonのわいひらさんのものが有名です。

しかしカテゴリーページから読み込むブログパーツにはそのカスタマイズは反映されません。
そこで入れ子のブログパーツからでも、広告を挿入できるように手を加えてみましたのでご紹介します。
SWELLでブログパーツにも広告を挿入するカスタマイズ
SWELLでブログパーツにも見出し上に広告を挿入するカスタマイズは、functions.phpのコードを挿入するだけです。
広告のコードを挿入
基本ですが、アドセンスのコードを下記に仕込んでおきましょう。
WordPressの管理画面 > SWELL設定 > 広告コード > 記事内広告
functions.phpのコードを挿入する
コードを記述する場所は下記になります。
WordPressの管理画面 > 外観 > テーマファイルエディター > functions.php
functions.phpに下記のコードを挿入してください。
function adsense_h2($the_content) {
$ad = do_shortcode('');
if ( is_single()|| is_category() ) {
$h2 = '/^<h2.*?>.+?<\/h2>$/im';
if ( preg_match_all( $h2, $the_content, $h2s )) {
if ( $h2s[0][1] ) {
$the_content = str_replace($h2s[0][1], $ad.$h2s[0][1], $the_content);
}
if ( $h2s[0][2] ) {
$the_content = str_replace($h2s[0][2], $ad.$h2s[0][2], $the_content);
}
if ( $h2s[0][3] ) {
$the_content = str_replace($h2s[0][3], $ad.$h2s[0][3], $the_content);
}
if ( $h2s[0][4] ) {
$the_content = str_replace($h2s[0][4], $ad.$h2s[0][4], $the_content);
}
if ( $h2s[0][5] ) {
$the_content = str_replace($h2s[0][5], $ad.$h2s[0][5], $the_content);
}
if ( $h2s[0][6] ) {
$the_content = str_replace($h2s[0][6], $ad.$h2s[0][6], $the_content);
}
}
}
}
return $the_content;
}
add_filter('the_content','adsense_h2',100);
引用 : https://nelog.jp/add-ads-before-h2
$ad = do_shortcode('');
で入れ子のブログパーツにも広告が挿入できます。
|| is_category()
でカテゴリーページにもコードを反映させます。
AdSense サイト運営者向けポリシー違反対応
もしポリシー違反などで特定の記事に広告を表示したいくない時は、if文の条件を足してあげるとよいです。
以下、対応方法を記載しておきます。
タグの作成とタグ付け
まず、広告無しというタグを作成して、該当する記事にタグ付けしてあげます。
広告無し(スラッグ名は no-ads)というタグを作成して広告を非表示にしたい記事に設定しておきました。

コードの修正
あとは先ほどのコードに条件を足してあげるだけです。
3行目に条件を付け加えておきました。
&&!in_array($tag->slug, array("no-ads"))
function adsense_h2($the_content) {
$ad = do_shortcode('');
if ( is_single()|| is_category() &&!in_array($tag->slug, array("no-ads"))) {
$h2 = '/^<h2.*?>.+?<\/h2>$/im';
if ( preg_match_all( $h2, $the_content, $h2s )) {
if ( $h2s[0][1] ) {
$the_content = str_replace($h2s[0][1], $ad.$h2s[0][1], $the_content);
}
if ( $h2s[0][2] ) {
$the_content = str_replace($h2s[0][2], $ad.$h2s[0][2], $the_content);
}
if ( $h2s[0][3] ) {
$the_content = str_replace($h2s[0][3], $ad.$h2s[0][3], $the_content);
}
if ( $h2s[0][4] ) {
$the_content = str_replace($h2s[0][4], $ad.$h2s[0][4], $the_content);
}
if ( $h2s[0][5] ) {
$the_content = str_replace($h2s[0][5], $ad.$h2s[0][5], $the_content);
}
if ( $h2s[0][6] ) {
$the_content = str_replace($h2s[0][6], $ad.$h2s[0][6], $the_content);
}
}
}
}
return $the_content;
}
add_filter('the_content','adsense_h2',100);
以上で広告無しというタグの記事には広告が表示されなくなります。
まとめ
本記事ではブログパーツにも広告を挿入するカスタマイズを紹介いたしました。
Googleアドセンスの自動広告はサイトの表示崩れやUXを損なってしまうので、まだまだ自分で意図した場所に広告をいれることをおすすめします。
記事中の見出しh2の上に広告を張ることは、効果が高く、記事の見た目もさほど損なわないのでおすすめです。
ぜひ本記事のカスタマイズを試してみてください。