我的代码会计算p
个代码,然后在第x个p
代码后插入广告代码。
如果我想要计算img
代码,请在第x img
个代码后插入广告代码,我该怎么做?
add_filter( 'the_content', 'prefix_insert_post_ads2' );
function prefix_insert_post_ads2( $content ) {
$imgs = preg_match_all("#<img.+>#U", $content, $matches);
$ad_codea = "ads code";
if ( is_single() && ! is_admin() && $imgs >= 4) {
return prefix_insert_after_paragraph2( $ad_codea, 3, $content );
}
return $content;
}
function prefix_insert_after_paragraph2( $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 );
}
答案 0 :(得分:1)
我自己解决了。
add_filter( 'the_content', 'prefix_insert_post_ads2' );
function prefix_insert_post_ads2( $content ) {
$imgs = preg_match_all("#<img.+>#U", $content, $matches);
preg_match_all('/<img[^>]+>/i',$content, $result);
$ad_codea = '123';
if ($imgs < 4 ) {$result[0][1]='';}
if ( is_single() && ! is_admin()) {
return str_replace($result[0][1], $result[0][1].$ad_codea, $content);
}
}