Skip to content

Instantly share code, notes, and snippets.

@nczz
Last active October 1, 2017 18:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nczz/aaf220302d6ba9afaf1886ed78ba8ed2 to your computer and use it in GitHub Desktop.
Save nczz/aaf220302d6ba9afaf1886ed78ba8ed2 to your computer and use it in GitHub Desktop.
WordPress 在文章中自動安插廣告碼
<?php
//functions.php
function mxp_insert_adcode_in_post($content) {
global $wp_current_filter;
$support_post_types = array("post");
if (!in_array(get_post_type(get_the_ID()),$support_post_types) || 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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment