我正在尝试在帖子的第一个h2标签之前插入广告。我尝试过的代码在下面,但是广告在内容之后而不是之前。我希望将广告插入内容之前,而不是之后。
/*Insert ads after second paragraph of single post content.*/
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = 'This is my ads';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 1, $content );
}
return $content;
}
//Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</h2>';
$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 :(得分:3)
尝试一下:
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '<h2>';
$paragraphs = explode( $closing_p, $content );
if ($paragraphs) {
$paragraphs[0] = $paragraphs[0].$insertion;
}
return implode( '<h2>', $paragraphs );
}