我将如何更改此代码,以便它在给定帖子的一半段落之后插入自定义内容?如果帖子有 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 );
}
Run Code Online (Sandbox Code Playgroud)
我不知道足够的 PHP 使其动态化。我在其他地方没有找到对此问题的动态答案。
我是这样解决的:
//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 );
}
Run Code Online (Sandbox Code Playgroud)
这里我还添加了类别检查。
| 归档时间: |
|
| 查看次数: |
2373 次 |
| 最近记录: |