WordPress文章Loop間插入廣告的作法

一般 WordPress 的網誌,擺設 Adsense 廣告的作法,大都是擺設在某一篇文章裡頭。很多人是使用 Adsense-Delux 插件來處理。擺設的位置就如同左圖,在文章 Loop 之外的頂端,或者是插入到文章的內文。這樣的處理方式,對於 Adsense 的點擊也許不算差。可不免還是有些處理上的麻煩。譬如說,若是首頁同時要顯示五篇文章。那只能在頭一篇裡頭擺廣告。第二篇或第三篇以後的文章就不能擺了。除非等到文章落入為第六篇之後,才另行加個廣告上去。要不然,第二篇以後的文章在獨立頁時就無法出現廣告了。固然,布落格首頁的 Adsense 也許是最重要的。單一文章頁暫時還沒設廣告上去,事後還是有補上的機會。不過,這樣的管理過程,畢竟還不是十分周延。於是,我們似該思考,是不要改成為在第一篇與第五篇文章的後頭來添加廣告。這又要面臨了一個,如何在五篇文章的 Loop 之中插入廣告的問題了。
WordPress 的使用說明中,提供了我們一個可行的方式。Advanced Topics »The WordPress Loop 之中,提到了這樣 Loop 分段的辦法。
我們以隨 WordPress 程式同時提供的內訂風格:kubrick,來討論如何修改 index.php 的內容。
kubrick的第 5 行與第 7 行,如下:
<?php if (have_posts()) :?>
<?php while (have_posts()) : the_post();?>
第 20 行則是:
<?php endwhile; ?>
說明書中的範例寫法如下:
<?php $my_query = new WP_Query(’category_name=featured&showposts=1′);
while ($my_query->have_posts()) : $my_query->the_post();
$do_not_duplicate = $post->ID;?>
<!– Do stuff… –>
<?php endwhile; ?>
<!– Do other stuff… –>
<?php if (have_posts()) : while (have_posts()) : the_post();
if( $post->ID == $do_not_duplicate ) continue; update_post_caches($posts); ?>
<!– Do stuff… –>
<?php endwhile; endif; ?>
範例中第一個 <!– Do stuff… –> 以上的部份,用來取代 kubrick的第 5 行與第 7 行。
範例中第二個 <!– Do stuff… –> 以下的部份,用來取代 kubrick的第 20 行。
至於,兩個 <!– Do stuff… –> 則是要填入 kubrick 的第 8 至 19 行之間的全部。
完成的程式改變就成為:
<?php $my_query = new WP_Query(’showposts=1′);
while ($my_query->have_posts()) : $my_query->the_post();
$do_not_duplicate = $post->ID;?>
<div class=”post” id=”post-<?php the_ID(); ?>”>
<h2><a href=”<?php the_permalink() ?>” rel=”bookmark” title=”Permanent Link to <?php the_title(); ?>”><?php the_title(); ?></a></h2>
<small><?php the_time(’F jS, Y’) ?> <!– by <?php the_author() ?> –></small>
<div class=”entry”>
<?php the_content(’Read the rest of this entry »’); ?>
</div>
<p class=”postmetadata”>Posted in <?php the_category(’, ‘) ?> | <?php edit_post_link(’Edit’, ”, ‘ | ‘); ?> <?php comments_popup_link(’No Comments »’, ‘1 Comment »’, ‘% Comments »’); ?></p>
</div>
<?php endwhile; ?>
<!– Do other stuff… 這個位置可擺第一篇文與第二篇文間的廣告 –>
<?php if (have_posts()) : while (have_posts()) : the_post();
if( $post->ID == $do_not_duplicate ) continue; update_post_caches($posts); ?>
<div class=”post” id=”post-<?php the_ID(); ?>”>
<h2><a href=”<?php the_permalink() ?>” rel=”bookmark” title=”Permanent Link to <?php the_title(); ?>”><?php the_title(); ?></a></h2>
<small><?php the_time(’F jS, Y’) ?> <!– by <?php the_author() ?> –></small>
<div class=”entry”>
<?php the_content(’Read the rest of this entry »’); ?>
</div>
<p class=”postmetadata”>Posted in <?php the_category(’, ‘) ?> | <?php edit_post_link(’Edit’, ”, ‘ | ‘); ?> <?php comments_popup_link(’No Comments »’, ‘1 Comment »’, ‘% Comments »’); ?></p>
</div>
<?php endwhile; ?>
<?php endwhile; endif; ?><!– Do other stuff… 這個位置可擺最後一篇文後的廣告 –>
=========================
* (修改後這段的第一行之中 new WP_Query(); 的參數, 我略有修改。)然後,兩個廣告就如上文所述的位置來安置。就 OK 了 !!













