本篇文章更新時間:2019/02/16
如有資訊過時或語誤之處,歡迎使用 Contact 功能通知。
一介資男的 LINE 社群開站囉!歡迎入群聊聊~
如果本站內容對你有幫助,歡迎使用 BFX Pay 加密貨幣 或 新台幣 贊助支持。
又正好處理到這件事,心想這件事一旦確定後,更新率實在不高,寫在子主題中 ``functions.php 保持彈性就好!
以下程式碼片段可以針對 <p></p>
標籤來計算段落,並且預設支援平均安插三個廣告碼在一整篇文章內,若該頁面段落數不足 11
則按照每 5
段安插(不會插滿三則)。這是目前測試到比較合理一點的感覺,若有其他規則,看得懂程式碼的人也可以自行調整參數!
<?php
//functions.php
function mxp_insert_adcode_in_post($content) {
global $wp_current_filter;
if (get_post_type(get_the_ID()) != 'post' || is_page() || is_feed() || is_archive() || is_home() || in_array('get_the_excerpt', (array) $wp_current_filter) || 'the_excerpt' == current_filter()) {
return $content;
}
$adcode_for_post_center01 = '<p><div id="mxp_ad_post_center01" style="text-align: center;">廣告碼01</div></p>';
$adcode_for_post_center02 = '<p><div id="mxp_ad_post_center02" style="text-align: center;">廣告碼02</div></p>';
$adcode_for_post_center03 = '<p><div id="mxp_ad_post_center03" style="text-align: center;">廣告碼03</div></p>';
$findme = '</p>';
$positions = array();
$pos = -1;
while (($pos = strpos($content, $findme, $pos + 1)) !== false) {
$content = substr_replace($content, '[mxp_ad_code_block]', $pos + strlen($findme), 0);
}
$positions = explode("[mxp_ad_code_block]", $content);
//每幾段安插一段廣告
$average = 5;
//亦可以判斷超過某段數後使用平均分散方式
$threshold = 11;
if (count($positions) > $threshold) {
$average = floor(count($positions) / 3);
}
$content_with_ad = "";
for ($i = 0; $i < count($positions); ++$i) {
if ($i == 0) {
$content_with_ad .= $positions[$i] . $adcode_for_post_center01;
continue;
}
if ($i == $average) {
$content_with_ad .= $positions[$i] . $adcode_for_post_center02;
continue;
}
if ($i == ($average * 2)) {
$content_with_ad .= $positions[$i] . $adcode_for_post_center03;
continue;
}
$content_with_ad .= $positions[$i];
}
return $content_with_ad;
}
add_filter('the_content', 'mxp_insert_adcode_in_post');
Gist: link
注意不要複製到第一行
<?php
,會導致在functinos.php
執行中發生錯誤! 還有當然就是自行替換廣告碼拉~XD