Products
GG网络技术分享 2025-03-18 16:12 0
如何在WordPress文章第二段或指定段落文字后插入广告代码或随机图片代码
1,用插件:
自动插入广告插件 Insert Post Ads
2,用代码:
主题的function文件中添加以下代码:
/*** WordPress 在文章内容中间插入广告
* http://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 );
}
Demand feedback