我一直在尝试使用add\\u filter将一些项目添加到WordPress内容的中间。该代码成功地将广告代码添加到WordPress内容的顶部,但没有插入。
以下是我使用的代码:
add_filter(\'the_content\', \'bbtre_amazon_content_filter\');
function bbtre_amazon_content_filter($content){
if(is_singular(\'post\')){
$count = explode(\'</p>\', $content);
foreach($count as $i => $paragraph){
$count = $i+1;
}
$content = explode(\'</p>\', $content);
foreach( $content as $index => $paragraph){
if(trim($paragraph)){
$content["{$index}"] .= \'</p>\';
}
if($index == intval($count/2)){
$ads = bbtre_the_amazon_items();
$content["{$index}"] .= $ads;
}
}
}
$content = (is_array($content)) ? implode($content) : $content;
return $content;
}
bbtre\\u中的亚马逊项目();
function bbtre_the_amazon_items(){
include(get_stylesheet_directory() .\'/inc/reshare/templates/ads/amazon.items.php\');
}
模板页面内:
<div class="amazon-item-wrap"><?php echo bbtre_get_amazon_items_list(); ?></div>
请任何人帮我解决这个问题。
注意:当我使用
$content["{$index}"] .= \'<p>Hello World</p>\';
而不是:
$content["{$index}"] .= $ads;
最合适的回答,由SO网友:obiPlabon 整理而成
您应该使用add_filter()
而不是apply_filters()
. apply_filters()
用于应用已注册的筛选器add_filter()
. 请检查以下代码以获取解决方案-
function bbtre_amazon_content_filter( $content ) {
if ( ! is_single() ) {
return $content; // Return early if not single post
}
// Paragraphs array without the closing tag
$paragraphs = explode( \'</p>\', $content );
// Number of paragraphs in $paragraphs
$paragraphs_count = count( $paragraphs );
// Middle index of $paragraphs
$middle_index = absint( floor( $paragraphs_count / 2 ) );
// New content string
$new_content = \'\';
for ( $i = 0; $i < $paragraphs_count; $i++ ) {
if ( $i === $middle_index ) {
// Add custom content in the middle of post contents
$new_content .= bbtre_the_amazon_items();
}
// Append the missing closing p tag
$new_content .= $paragraphs[ $i ] . \'</p>\';
}
return $new_content;
}
add_filter( \'the_content\', \'bbtre_amazon_content_filter\' );