我试图在帖子的第一个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 );
}
任何帮助都将不胜感激。
最佳答案
试试这个:
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 );
}