小编Spa*_*lot的帖子

在 WordPress 帖子中间添加自定义内容

我将如何更改此代码,以便它在给定帖子的一半段落之后插入自定义内容?如果帖子有 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 …
Run Code Online (Sandbox Code Playgroud)

php wordpress

1
推荐指数
1
解决办法
2373
查看次数

标签 统计

php ×1

wordpress ×1