WordPressで各記事の最後にGoogle Adsenseの広告を貼り付ける方法のメモ

WordPressで各記事の最後にGoogle Adsenseの広告を貼り付ける方法のメモ。

自分のブログはサイドバーにGoogle Adsense広告を貼り付けているが、もう少し広告の数を増やそうと思い立った。

条件としては

  • Google Adsenseの自動広告機能は手当たり次第に広告を出現させて美しくないので使いたくない。
  • なるべく記事を読むときに邪魔にならない位置に広告を貼りたい。
  • ↑とはいえ、そこそこ目に付く位置には貼りたい。

よって、各記事の最後に広告を貼ろうと決めた。(これなら記事を最後までスクロールしないと広告が現れないので邪魔にならないはず。。)

WordPressで各記事の任意の位置に一括で広告を挿入する方法についてググってみたところ、プラグインを利用した方法やfunctions.phpを編集する方法が紹介されていたが、自分のケースではsingle.phpを編集する方法が良さそうに感じた。

以下の手順で広告を挿入した。

まずはfindコマンドで自分が使用しているWordPressテーマのsingle.phpを見つける。

find /path/to/documentroot -name single.php

対象のsingle.phpを見つけたら、作業前に必ずバックアップを取っておく。

cp single.php single.php.bak.$(date -u '+%Y-%m-%d-%H%M%S_UTC')

また、今回は前日にDigital Oceanの自動バックアップが走っていたのでやらなかったが、作業前にはサーバーのバックアップも取っておくのが望ましい。

single.phpを眺めてみたところ、get_template_part()の直後にGoogle Adsenseのコードを挿入すれば良さそうに感じた。

<?php get_header(); ?>

<?php
/**
 * TheSimplest Layout Options
 */
$thesimplest_site_layout    =   get_theme_mod( 'thesimplest_layout_options_setting' );
$thesimplest_layout_class   =   'col-md-8 col-sm-12';

if( $thesimplest_site_layout == 'left-sidebar' && is_active_sidebar( 'sidebar-1' ) ) :
	$thesimplest_layout_class = 'col-md-8 col-sm-12  site-main-right';
elseif( $thesimplest_site_layout == 'no-sidebar' || !is_active_sidebar( 'sidebar-1' ) ) :
	$thesimplest_layout_class = 'col-md-8 col-sm-12 col-md-offset-2';
endif;

?>

	<div id="primary" class="content-area row">
		<main id="main" class="site-main <?php echo esc_attr($thesimplest_layout_class); ?>" role="main">

			<?php
			// Start the loop
			while( have_posts() ) : the_post();

                // Include the single post content template.
                get_template_part( 'template-parts/content', 'single' );

                if( is_singular( 'attachment' ) ) {
	                // Parent post navigation.
                    the_post_navigation( array(
                            'prev_text'     =>  _x( '<span class="meta-nav">Published in</span><span class="post-title">%title</span>', 'Parent post link', 'thesimplest' ),
                    ) );
                } elseif( is_singular( 'post' ) ) {
	                // Previous/next post navigation.

get_template_part( 'template-parts/content', 'single' );の直後に以下のコードを挿入してsingle.phpを保存した。(自分向けメモ:コピペする際はインデントに注意すること)

$ad = <<< EOF
insert your Google Adsense code here
EOF;
print($ad); //load adsense code

編集が完了して数十秒ほどで以下のように広告が出現した。

本音を言えば画像よりもう少し上の位置に広告を表示させたかったのだが、自分の使用しているWordPressテーマのデザイン上、これが限界だった。

Leave a Reply

Your email address will not be published. Required fields are marked *