Simplicityなどのよくできているテーマだと、Google Adsenseのコードはウィジェットを設定するだけで簡単に設定することができます。
しかし、海外テーマなどテーマを使う場合などには、広告を入れたい場所に入れられないことがあります。
好きな場所にGoogle Adsenseのコードを入れたい場合は、どうすればよいのでしょうか。
[toc]
基本的なコード
phpの形式で書くことにより、テーマをカスタマイズして、Google Adsenseのコードを入れることができます。
モバイルとPCとで表示する広告を分けたい場合は、wp_is_mobile()という関数を使います。ただし、この関数はタブレットもモバイルとして扱われますので、注意してください。
下記のような形になります。content-single.phpなどの名前がついている、投稿を表示するphpを編集することで広告を表示することができます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
if ( wp_is_mobile() ) { <br>スポンサーリンク<br> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- レスポンシブ 記事中 --> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-xxxxxxxxxxxxxxxx" data-ad-slot="xxxxxxxxxx" data-ad-format="auto"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> } else { <br>スポンサーリンク<br> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- レクタングル(大)記事中 --> <ins class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-xxxxxxxxxxxxxxxx" data-ad-slot="xxxxxxxxxx"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> } |
ToC+と連携して、最初の見出し2(h2)の前に広告を入れる
次は私がよくやっているやり方です。
目次の次に広告を表示する、というのをよくやっています。たとえば、こんな感じになります。
Simplicityで言うところの、文中に広告を入れる(最初の見出し2の前に広告を入れる)と同じですね。
これをやりたい場合は、ToC+のコードをカスタマイズする必要があります。
下記のファイルを編集します。
wp-content/plugins/table-of-contents-plus/toc.php
下記のように書かれている場所を探します。これが目次の部分の終端です。
1 |
$html .= '<ul class="toc_list">' . $items . '</ul></div>' . "\n"; |
そのすぐ下に下記の記述を追記しましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
if ( wp_is_mobile() ) { $html .= '<br>スポンサーリンク<br> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- レスポンシブ 記事中 --> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-xxxxxxxxxxxxxxxx" data-ad-slot="xxxxxxxxxx" data-ad-format="auto"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script>'; } else { $html .= '<br>スポンサーリンク<br> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- レクタングル(大)記事中 --> <ins class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-xxxxxxxxxxxxxxxx" data-ad-slot="xxxxxxxxxx"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script>'; } |
これで目次のすぐ下に広告が表示されるはずです。
まとめ
テーマによってはウィジェットを設定するだけでは、入れたい場所に広告を入れられない場合があります。その場合はテーマやプラグインのコードをカスタマイズしましょう。
コメント