本文目錄1使用 Insert Post Ads 外掛2純代碼實現
不少朋友希望在文章內容的中間插入廣告(認為這個對用戶體驗有點不太好),下面就來看看如何實現吧。
使用 Insert Post Ads 外掛
Insert Post Ads 是一個非常簡單易用的外掛,可以在文章和頁面中的不同段落插入多個不同廣告,你需要做的隻是在後臺新建廣告,然後選擇插入的段落位置即可。
在後臺外掛安裝界面搜索 Insert Post Ads 即可線上安裝,或者到 WordPress官方外掛庫下載。已將該外掛漢化(部分詞條無法應用語言包),下載簡體中文包,解壓後上傳到該外掛的 languages 目錄即可。
純代碼實現
如果你隻想添加簡單的廣告代碼,不想用外掛,那你可以將下面的代碼添加到當前主題的 functions.php 即可:
註意按照下面的註釋修改廣告代碼和段落
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
/** * WordPress 在文章內容中間插入廣告 * https://www.wpdaxue.com/insert-ads-within-post-content-in-wordpress.html */ //在文章內容的第二段後面插入廣告 add_filter( 'the_content', 'prefix_insert_post_ads' ); function prefix_insert_post_ads( $content ) { $ad_code = '<div>添加你的廣告代碼</div>'; if ( is_single() && ! is_admin() ) { // 修改 2 這個段落數 return prefix_insert_after_paragraph( $ad_code, 2, $content ); } return $content; } // 插入廣告所需的功能代碼 function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) { $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] .= $insertion; } } return implode( '', $paragraphs ); } |
/**
* WordPress 在文章內容中間插入廣告
* https://www.wpdaxue.com/insert-ads-within-post-content-in-wordpress.html
*/
//在文章內容的第二段後面插入廣告
add_filter( ‘the_content’, ‘prefix_insert_post_ads’ );
function prefix_insert_post_ads( $content ) {
$ad_code = ‘<div>添加你的廣告代碼</div>’;
if ( is_single() && ! is_admin() ) {
// 修改 2 這個段落數
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
} // 插入廣告所需的功能代碼
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$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] .= $insertion;
}
}
return implode( ”, $paragraphs );
}
參考資料:http://www.wpbeginner.com