将代码放在 X 段之后


Place code after X paragraphs

我用它来在帖子中指定数量的段落之后放置代码,但我不知道除了结束之外如何</p>还识别</h3>

谢谢!

function adify_paragraphs($content) {
    $tmp = $content;
    $tmp = explode('</p>',$content);
    $adcode = 'additional code 1';
    $adcode2 = 'additional code 2';
    if (count($tmp)>3):
        array_splice($tmp,1,0,$adcode);
    endif;
    if (count($tmp)>9):
        array_splice($tmp,7,0,$adcode2);
    endif;
    $cc = implode('<p/>',$tmp);
    return $cc;
}
add_filter( 'the_content', 'adify_paragraphs');

想出了一个可能不优雅的解决方案,但它有效。它的作用是在每个第 2 段之后添加一个额外的段落,如果它后面没有 H3。

function adify_paragraphs($content) {
    // Splitting the content into an array of paragraphs and headers.
    preg_match_all('/<h3>.*<'/h3>|<p>.*<'/p>/imU', $content, $matches);
    $count = count($matches[0]);
    if (empty($count)) {
        // Nothing to work with.
        return $content;
    }
    $p_count = 0;
    for ($i = 0; $i < $count; $i++) {
        // Increment the paragraph counter if we meet a paragraph.
        // Otherwise, reset it.
        if (strpos($matches[0][$i], '<p>') !== FALSE) {
            $p_count++;
        } else {
            $p_count = 0;
        }
        if ($p_count == 2 && strpos($matches[0][$i+1], '<h3>') === FALSE) {
            // Insert the additional code and reset the counter.
            $content = str_replace($matches[0][$i], $matches[0][$i].'<p>AD!</p>', $content);
            $p_count = 0;
        }
    }
    return $content;    
}

如果您需要以其他方式插入广告,请将2更改为任何其他数字(不幸的是,从您的代码中不太清楚)。

您可以在此处看到它的工作:https://eval.in/521508