Table of Contents
<p>透過自訂PHP函數為WordPress解鎖變現潛力刊登Google AdSense文章內廣告。提升性能、增強安全性並獲得精確的廣告控制。學習基本設定' 進階廣告位置,和模組化解決方案。</p>
準備好從你的WordPress網站產生收入了嗎?雖然Google AdSense在2023年仍然是部落格變現的首選,但大多數站長依賴的外掛可能會拖慢網站速度。在這篇完整的介紹中,我將示範如何使用自訂PHP函數刊登Google AdSense文章內廣告,這種方式提供卓越的性能、增強的安全性,以及像素級精確的廣告位置控制。
為何自訂PHP函數優於AdSense外掛
WordPress資源庫提供了數十種AdSense外掛,但精明的開發者越來越傾向於自訂PHP解決方案。原因如下:
- 閃電般的速度:自訂程式碼消除了外掛帶來的臃腫,根據WP Rocket的性能研究,頁面載入時間最多可減少30%
- 堅固的安全性:能彈性修正常見的外掛漏洞,最大限度減少駭客的可攻擊途徑
- 精準定位:將廣告放置在最佳表現位置——特定段落之後、圖片之間或內容中的上下文位置
- 替未來作好準備:在WordPress更新、主題變更和Google AdSense政策更新過程中,你的廣告繼續完美運作
- 更簡潔的WordPress儀表板:享受精簡的管理體驗,沒有額外的外掛選單佔用你的工作空間
設定Google AdSense帳戶
在深入研究程式碼之前,請先確認你的AdSense帳戶已正確設定,包含:
- 申請AdSense帳戶:確保你的網站有優質原創內容、專業設計和必要的法律頁面(隱私政策、服務條款)
- 新增廣告單元(Ad unit):登入你的AdSense儀表板並為不同位置建立響應式廣告單元。根據本文的主題,你需要新增in-article ads。
- 啟用自動廣告(可選):在實施自訂位置的同時,考慮啟用AdSense自動廣告作為備用策略
- 驗證合規性:查看最新的AdSense計劃政策,確保你的實施符合規定

基礎級 – 設定廣告程式碼
讓我們從一個簡單但強大的函數開始,該函數可以在文章的特定段落後自動插入廣告:
// 在特定段落後插入廣告的函數
function insert_adsense_after_paragraph($content) {
// 僅在單篇文章中顯示廣告
if (!is_single()) {
return $content;
}
// 你的AdSense程式碼(替換為你實際的廣告程式碼)
$ad_code = '<div class="adsense-container">
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-XXXXXXXXXX"
data-ad-slot="XXXXXXXXXX"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>';
// 在哪個段落後放置廣告
$paragraph_id = 3;
// 按段落分割內容
$closing_p = '</p>';
$paragraphs = explode($closing_p, $content);
// 遍歷段落並插入廣告
foreach ($paragraphs as $index => $paragraph) {
if (trim($paragraph)) {
$paragraphs[$index] .= $closing_p;
}
if ($paragraph_id == $index + 1) {
$paragraphs[$index] .= $ad_code;
}
}
return implode('', $paragraphs);
}
// 將函數增加到過濾器
add_filter('the_content', 'insert_adsense_after_paragraph');只需將此程式碼添加到你主題的functions.php檔案中,用你從Google獲取的實際廣告單元程式碼替換佔位廣告程式碼即可。
進階級 – 策略性多廣告位置
為了最大化收入潛力,你需要在較長的內容中放置多個廣告。這種進階策略能將廣告在最佳閱讀位置:
// 廣告插入的父函數
function insert_ad_after_paragraph($insertion, $paragraph_id, $content) {
$closing_p = '</p>';
$paragraphs = explode($closing_p, $content);
$paragraphs_count = count($paragraphs);
foreach ($paragraphs as $index => $paragraph) {
if (trim($paragraph)) {
$paragraphs[$index] .= $closing_p;
}
// 如果文章段落少於指定數量,則在最後一段添加廣告
if (($paragraph_id > $paragraphs_count) && ($paragraphs_count == $index + 1)) {
$paragraphs[$index] .= $insertion;
}
// 否則在指定位置插入
else if ($paragraph_id == $index + 1) {
$paragraphs[$index] .= $insertion;
}
}
return implode('', $paragraphs);
}
// 處理多個廣告插入的函數
function insert_multiple_adsense_ads($content) {
// 僅在單篇文章中顯示廣告,且不在管理界面
if (!is_single() || is_admin()) {
return $content;
}
// 第一個廣告程式碼(第3段後)
$ad_code1 = '<div class="adsense-container">
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-XXXXXXXXXX"
data-ad-slot="XXXXXXXXXX"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>';
// 第二個廣告程式碼(第8段後)
$ad_code2 = '<div class="adsense-container">
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-XXXXXXXXXX"
data-ad-slot="YYYYYYYYYY"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>';
// 插入第一個廣告
$content = insert_ad_after_paragraph($ad_code1, 3, $content);
// 插入第二個廣告
$content = insert_ad_after_paragraph($ad_code2, 8, $content);
return $content;
}
// 掛鉤函數
add_filter('the_content', 'insert_multiple_adsense_ads');這種設計方式能自動處理較短的內容,確保只有在有足夠段落時才顯示廣告,防止可能觸發AdSense政策違規的尷尬廣告堆疊。
專業級 – 建立模組化解決方案
身為一個專業開發者,模組化程式碼是避免遺留技術債的重要步驟。以下是如何像專業人士一樣構建你的AdSense模組:
- 在你的主題資料夾中建立一個專用目錄:
/wp-content/themes/your-theme/inc/ - 在該目錄中建立一個名為
adsense-functions.php的檔案 - 將所有AdSense函數移至此檔案,此文章底部會提供完整程式碼,不需要自己手動剪剪貼貼
- 在functions.php中使用引入adsense-functions.php:
// 包含AdSense功能
require_once get_template_directory() . '/inc/adsense-functions.php';如果你使用子主題(強烈推薦),請使用:
require_once get_stylesheet_directory() . '/inc/adsense-functions.php';這種方法使你的程式碼更易於維護,更容易更新或轉移到其他網站。
進階功能:短代碼和排除邏輯
自訂短代碼以手動控制廣告
有時你需要手動控制廣告位置。這個短碼給你提供了這種靈活性:
// 新增[adsense]短代碼
function adsense_shortcode($atts) {
$atts = shortcode_atts(array(
'slot' => 'default-slot',
'class' => '',
), $atts);
return '<div class="adsense-container ' . esc_attr($atts['class']) . '">
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-XXXXXXXXXX"
data-ad-slot="' . esc_attr($atts['slot']) . '"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>';
}
add_shortcode('adsense', 'adsense_shortcode');現在你可以在文章中的任何位置使用[adsense]或[adsense slot="your-slot-id" class="custom-style"]來精確放置廣告。
自動廣告排除邏輯
並非所有內容都適合變現。此函數幫助你選擇性地禁用廣告:
// 決定是否應該顯示廣告的函數
function should_show_ads() {
// 不在這些分類中顯示廣告
if (is_category(array('announcements', 'sponsored'))) {
return false;
}
// 不在這些特定文章中顯示廣告
$excluded_posts = array(123, 456, 789); // 文章ID
if (is_single($excluded_posts)) {
return false;
}
// 排除帶有'no-ads'元值的文章
if (is_single() && get_post_meta(get_the_ID(), 'no_ads', true) == 'yes') {
return false;
}
return true;
}然後修改你的廣告插入函數,在顯示廣告前檢查此項:
if (!is_single() || is_admin() || !should_show_ads()) {
return $content;
}策略性廣告位置:最大化點擊率和收入
根據Ezoic在2022年的研究,廣告位置顯著影響點擊率和收入。這些高效位置值得你關注:
- 首屏位置:使用無需滾動即可看到的廣告立即吸引注意力
- 第一段落之後:讀者已經參與但尚未完全投入內容
- 內容中間斷點:內容流中的自然停頓,讀者可能考慮點擊
- 文章結尾位置:利用已閱讀完你內容並正在決定下一步行動的讀者
- 側邊欄配套廣告:用上下文相關的側邊欄位置補充內容中的廣告
請記住,Google限制每頁AdSense廣告單元不超過3個。策略性地放置它們,而不是全部擠在頂部。
專業廣告樣式提高點擊率
廣告的呈現方式顯著影響其表現。將此CSS添加到你的主題,確保廣告看起來精美且響應式:
.adsense-container {
text-align: center;
margin: 25px 0;
padding: 5px 0;
overflow: hidden;
clear: both;
background: #fafafa;
border-radius: 4px;
transition: all 0.3s ease;
}
.adsense-container:hover {
background: #f5f5f5;
}
@media (max-width: 768px) {
.adsense-container {
margin: 15px 0;
padding: 3px 0;
}
}這種樣式建立了一個微妙的容器,將廣告與內容區分開來而不顯得突兀,而懸停效果可以增加互動。
完整PHP模組
<?php
/**
* File: /wp-content/themes/your-theme/inc/adsense-functions.php
* AdSense integration functions for WordPress
*/
// Prevent direct access
if (!defined('ABSPATH')) {
exit;
}
class WP_AdSense_Integration {
private $publisher_id = 'ca-pub-your-publisher-id'; // Replace with your publisher ID
private $default_ad_slot = 'your-default-ad-slot'; // Replace with your default ad slot
public function __construct() {
$this->init_hooks();
}
/**
* Initialize WordPress hooks
*/
private function init_hooks() {
// Choose which method to use by uncommenting the desired line
add_filter('the_content', array($this, 'insert_ad_after_paragraph'));
// add_filter('the_content', array($this, 'insert_ad_at_beginning'));
// add_filter('the_content', array($this, 'insert_ad_at_end'));
add_filter('the_content', array($this, 'insert_multiple_ads'));
// Add shortcode support
// add_shortcode('adsense', array($this, 'adsense_shortcode'));
}
/**
* Check if ads should be displayed
*/
private function should_show_ads() {
// Only show on single posts
if (!is_single() || !is_main_query()) {
return false;
}
// Exclude specific post IDs
$excluded_posts = array(123, 456, 789); // Replace with actual post IDs
if (in_array(get_the_ID(), $excluded_posts)) {
return false;
}
// Exclude specific categories
$excluded_categories = array('uncategorized', 'private'); // Replace with actual category slugs
if (has_category($excluded_categories)) {
return false;
}
return true;
}
/**
* Generate AdSense ad code
*/
private function get_ad_code($slot_id = null, $css_class = 'adsense-ad', $style = 'text-align: center; margin: 20px 0;') {
$slot = $slot_id ? $slot_id : $this->default_ad_slot;
return '
<div class="' . esc_attr($css_class) . '" style="' . esc_attr($style) . '">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=' . $this->publisher_id . '"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="' . $this->publisher_id . '"
data-ad-slot="' . esc_attr($slot) . '"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>';
}
/**
* Insert ad after specific paragraph
*/
public function insert_ad_after_paragraph($content) {
if (!$this->should_show_ads()) {
return $content;
}
$paragraphs = explode('</p>', $content);
$paragraph_count = count($paragraphs);
// Insert ad after 4nd paragraph
if ($paragraph_count >= 5) {
$ad_code = $this->get_ad_code(null, 'adsense-after-paragraph');
$paragraphs[3] .= '</p>' . $ad_code;
}
return implode('</p>', $paragraphs);
}
/**
* Insert ad at the beginning of posts
*/
public function insert_ad_at_beginning($content) {
if (!$this->should_show_ads()) {
return $content;
}
$ad_code = $this->get_ad_code(null, 'adsense-beginning', 'text-align: center; margin-bottom: 20px;');
return $ad_code . $content;
}
/**
* Insert ad at the end of posts
*/
public function insert_ad_at_end($content) {
if (!$this->should_show_ads()) {
return $content;
}
$ad_code = $this->get_ad_code(null, 'adsense-end', 'text-align: center; margin-top: 20px;');
return $content . $ad_code;
}
/**
* Insert multiple ads based on content length
*/
public function insert_multiple_ads($content) {
if (!$this->should_show_ads()) {
return $content;
}
$word_count = str_word_count(strip_tags($content));
// Only insert ads for longer posts
if ($word_count < 500) {
return $content;
}
$paragraphs = explode('</p>', $content);
$total_paragraphs = count($paragraphs);
// Insert ads every 3 paragraphs for very long posts
if ($word_count > 800) {
for ($i = 2; $i < $total_paragraphs - 1; $i += 4) {
if (isset($paragraphs[$i])) {
$ad_code = $this->get_ad_code(null, 'adsense-inline', 'text-align: center; margin: 25px 0;');
$paragraphs[$i] .= '</p>' . $ad_code;
}
}
} else {
// Insert one ad after 2nd paragraph
if ($total_paragraphs >= 5) {
$ad_code = $this->get_ad_code(null, 'adsense-inline', 'text-align: center; margin: 25px 0;');
$paragraphs[1] .= '</p>' . $ad_code;
}
}
return implode('</p>', $paragraphs);
}
/**
* AdSense shortcode
*/
public function adsense_shortcode($atts) {
$atts = shortcode_atts(array(
'slot' => $this->default_ad_slot,
'class' => 'adsense-shortcode',
'style' => 'text-align: center; margin: 20px 0;'
), $atts);
return $this->get_ad_code($atts['slot'], $atts['class'], $atts['style']);
}
}
// Initialize the AdSense integration
function init_adsense_integration() {
new WP_AdSense_Integration();
}
add_action('init', 'init_adsense_integration');
?>AdSense常見錯誤
即使完美的程式碼也可能遇到問題。以下是如何排除常見問題:
- 廣告未正常顯示:AdSense可能需要24-48小時才能開始在新單元中顯示廣告。如果它們仍未出現,請檢查你的瀏覽器控制台是否有JavaScript錯誤。
- 破版:如果廣告破壞了你的版面,請檢查你的CSS並確保
.adsense-container類有適當的樣式。自動廣告通常是破版的原因之一。 - 廣告出現在錯誤頁面:使用
is_single()和其他WordPress條件標籤驗證你的條件邏輯。 - 政策違規:檢查你的AdSense儀表板是否有任何政策問題。常見問題包括廣告放置過近或靠近互動元素。
- 低獲益:參考Google的AdSense官方說明,調整廣告版位與格式改善以改善成效。
結論:自訂PHP的優勢
使用自訂PHP函數刊登Google AdSense文章內廣告,讓你比依賴外掛的競爭對手擁有顯著優勢。你將享受更快的頁面載入、增強的安全性和對廣告位置的精確控制,所有這些因素都有助於提供更好的用戶體驗和更高的收入。
本文中概述的方法為自動和手動廣告插入提供了強大的框架,同時保持乾淨、有組織的程式碼。隨著流量增長,你可以輕鬆調整廣告配置以最大化收益,而不犧牲性能。
從基本設定開始,然後隨著你對程式碼越來越熟悉,逐漸納入進階功能。定期監控你的AdSense儀表板,識別哪些位置表現最佳,並相應調整你的策略。
你是否在WordPress網站中成功使用了自訂AdSense函數?與基於外掛的解決方案相比,你看到了什麼結果?在下方留言中分享你的經驗!




