直接上代码,然后将代码复制到主题目录下的functions.php里使用即可,如果报错请根据自身代码进行修改。

function themeInit($archive) {
    // 判断是否是文章,如果是就插入广告
    $ad_code = '<div>这是你的广告</div>';
    if ($archive->is('single')) {
        $archive->content = prefix_insert_after_paragraph( $ad_code, 2, $archive->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 );
}

来源:https://www.hurbai.com/typecho/108