我将如何更改此代码,以使其在给定帖子的一半段落之后插入自定义内容?如果帖子包含12个段落,则内容应在数字6之后插入。如果帖子具有100,则应在数字50之后插入内容。
我在网上找到了此代码,您可以在其中指定段落的硬编码数量:
<?php
//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 = '<div>Ads code goes here</div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
}
// Parent Function that makes the magic happen
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 );
}
我不知道足够的PHP使它动态。我没有在其他地方找到对此的动态答案。
答案 0 :(得分:0)
我这样解决了:
//Insert ads after half of the paragraphs in a post
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '<div>CODE HERE</div>';
if ( is_single() && ! is_admin() && in_category('29') ) {
return prefix_insert_after_paragraph( $ad_code, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
$paragraph_id = round(count($paragraphs) / 2);
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
在这里,我还添加了类别检查。