wordpress在所有文章第二段落中插入广告的方法

将下面这段代码添加到网站根目录下functions.php文件中,添加到文件的最后即可。如果添加了没有生效,先清空缓存试试,再看看使用的主题模板是否有单独的functions.php自定义文件调用。

function insert_after_first_paragraph($content) {
if (!is_single()) return $content;

$content_parts = explode('</p>', $content);
if (count($content_parts) > 1) {
$inserted_content = '<div class="inserted-content centered-content">这里改成广告代码或超链接</div>';
$content_parts[0] .= '</p>' . $inserted_content;
$content = implode('</p>', $content_parts);
}
return $content;
}
add_filter('the_content', 'insert_after_first_paragraph');

function add_custom_styles() {
echo '<style>
.centered-content {
text-align: center;
margin: 20px 0;
}
.inserted-link {
* 这里不需要定义颜色,让它继承主题样式 */
font-weight: bold; /* 可选:使链接更明显 */
}
</style>';
}
add_action('wp_head', 'add_custom_styles');

版权声明:本文由 鹿泽笔记 原创发布。

本文链接:https://www.bailuze.com/18581.html

许可协议:本文标题《wordpress在所有文章第二段落中插入广告的方法》,转载请注明文章出处及原始链接。

鹿泽
鹿泽

深耕 SEO优化 十二年,从个人博客爱好者到专业谷歌优化顾问的成长之路。技术派SEO、全域流量技术运营专家,拥有多年从业经验,热衷于分析算法逻辑与推理的精准匹配。