記事内に広告が含まれています。

トップページやアーカイブページの任意の記事の下に広告を入れる

wordpressに広告を表示する wordpressでブログを作ろう

 トップページやアーカイブページに複数の記事が表示されるように設定している場合に、任意の記事の下だけに広告を表示するようにしてみよう。

 基本は同じだが、テーマによってコードの記載の仕方が一寸違う。

 STINGER3とTwenty Fourteenの場合で任意の記事の下に広告などを入れる方法をメモしておく。

 もちろん、広告だけでなく画像や定型文を表示することも出来る。

広告

複数記事表示で任意の記事の下に広告を入れる方法・基本

1、while (have_posts()) : the_post();を探す。

2、while (have_posts()) : the_post();を以下の記述に書き換える。

while (have_posts()) : the_post(); $counter++;

3、書き換えた記述の下に以下の記述を追加する。

<?php if ($counter == 2) {
print <<<EOD
広告コードを挿入
EOD;
} ?>

 ひとつ目の記事の下に広告などが表示される。

 2つ目の記事の下に記事を表示したい場合場合数字を3へ変える。

  ($counter ==  2)に不必要なスペースなどが入るときちんと表示されないので注意。

広告

複数記事表示で任意の記事の下に広告を入れる方法・STINGER3の場合

 <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>を以下の記述に書き換える。

<?php if ( have_posts() ) : while (have_posts()) : the_post(); $counter++; ?>
<?php if ($counter == 2) {
print <<<EOD
広告コードを挿入
EOD;
} ?>

複数記事表示で任意の記事の下に広告を入れる方法・Twenty Fourteenの場合

 wordpressのデフォルトテーマTwenty Fourteenの場合はもう少し工夫がいる。

 Twenty Fourteenのトップページのphp(index.php)の該当部分を見ていると以下のような記述になっている。

<?php
   if ( have_posts() ) :
    // Start the Loop.
    while ( have_posts() ) : the_post();
     /*
      * Include the post format-specific template for the content. If you want to
      * use this in a child theme, then include a file called called content-___.php
      * (where ___ is the post format) and that will be used instead.
      */
     get_template_part( 'content', get_post_format() );
    endwhile;
    // Previous/next post navigation.
    twentyfourteen_paging_nav();
   else :
    // If no content, include the "No posts found" template.
    get_template_part( 'content', 'none' );
   endif;
  ?>

  【while ( have_posts() ) : the_post();】の部分は素直に【while (have_posts()) : the_post(); $counter++;】に書き換えればOK。

 でも、<?php if ($counter ==  2) {print <<<EOD広告コードを挿入EOD;} ?>をそのまま記入するとエラーになる。

 実際にTwenty Fourteenのテーマに貼り付けるのは以下の記述になる。

 if ($counter ==  2) {
print <<<EOD
広告コードを挿入
EOD;
}

 まとめると以下のようになる。

1、【while ( have_posts() ) : the_post();】を探す。

2、【while ( have_posts() ) : the_post();】を以下の記述に書き換える。

while (have_posts()) : the_post(); $counter++; if ($counter ==  2) {
print <<<EOD
広告コードを挿入
EOD;
}

 他のテーマはどうなのかわからないけど、皆様のご参考になれば。

コメント

タイトルとURLをコピーしました