この前、サイトを見てくれている方から、
賢威7の一番最初のh2タグの手前に、AdSense広告を横並びで2つ表示(ダブルレクタングルを表示)させる方法を教えてほしい
というコメントをいただいたので、今回は賢威7サイトにダブルレクタングルを表示させる方法を書いていきたいと思います。
参考にしたサイト(はぴすぷ さん):
【WordPress】1つ目のh2見出しの手前に広告を自動で挿入する【Google Adsenseポリシー違反対策込み】
2016年3月30日追記
スマホでは画面中に広告を2つ表示してはいけないらしいので、スマホの場合は広告を1つだけ表示するように変更しました。
モバイルサイトの場合は、2 つ以上の AdSense 広告を画面に同時に掲載することはできません。
カスタマイズ前
↓ 広告を表示する前の状態
カスタマイズ後
↓ 一番最初のh2の手前にAdSense広告を2つ横並びで表示
※ 今回はPHPファイルを編集していきます。管理画面に入れなくなることもあるので、PHPコードは注意して編集して下さい。
1. functions.php を編集
まずは広告を2つ表示させます。
functions.php に以下のコードを追加します。このとき編集する functions.php は、親テーマ(賢威7本体)のものでも子テーマのものでも、どちらでも大丈夫です。
※ 下のコードの <!-- Google Adsense の広告コード -->
にAdSenseコードを貼り付けて下さい。
2016年3月30日追記
スマホでは広告を1つだけ表示するように修正しました。
function content_h2_add_ad($the_content) {// 投稿のみ適用if (!is_single()) {return $the_content;}$ad = '<!-- Google Adsense の広告コード -->';// 広告と分かるようにするボックス$ad_content = '<div class="content-ad-wrap"><p>スポンサーリンク</p><div class="content-ad">' . $ad . '</div>';if ( !wp_is_mobile() ) {$ad_content .= '<div class="content-ad">' . $ad . '</div>';}$ad_content .= '</div>';// 正規表現で最初のh2の手前に広告ボックスを付ける$h2 = '/<h2.*/h2>/im';if ( preg_match( $h2, $the_content, $h2s )) {$the_content = preg_replace($h2, $ad_content.$h2s[0], $the_content, 1);}return $the_content;}add_filter('the_content','content_h2_add_ad');
↓ 編集後
2. style.css を編集
functions.php の編集でh2の手前に広告を2つ表示させることができたので、今度はCSSファイルを編集して広告を横並びにします。
以下のコードを子テーマの style.css に追加すると
.content-ad-wrap:before {content: "";display: table;}.content-ad-wrap:after {content: "";display: table;clear: both;}.content-ad-wrap {width: 100%;text-align: center;}.content-ad-wrap > p {color: #888;margin-bottom: 5px;}.content-ad {margin-bottom: 30px;}.content-ad:first-child {margin-right: 4%;}@media only screen and (min-width : 1200px){.content-ad-wrap {text-align: left;}.content-ad {width: 48%;float: left;}}
広告が横並びで表示されるようになりました。これで完成です。
↓ スマホ表示は1つのみ表示(PCで見た場合は横幅を狭めても広告が2つ表示されます)