在WordPress文章段落后添加自定义内容

WordPress6527阅读模式

如果想在WordPress文章段落后添加自定义内容,比如在文章第二段后添加广告,可以尝试用下面的代码:

在WordPress文章段落后添加自定义内容

在WordPress文章段落后添加自定义内容

section
// 在文章第二段之后插入内容
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
	$ad_code = '<div>添加的文字</div>';
	if ( is_single() && ! is_admin() ) {
		return prefix_insert_after_paragraph( $ad_code, 2, $content );
	}
return $content;
}
 
// 主要函数
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 );
}
section

分别在段落2、4、6后面添加不同的内容

add_filter( 'the_content', 'add_ads_to_content' );
function add_ads_to_content( $content ) {
	$ads = array(
		2 =>  'ad code 1', // paragraph_id => ad_code
		4 => 'ad code 2', // paragraph_id => ad_code
		6 => 'ad code 3' // paragraph_id => ad_code
	);

	if ( is_single() && ! is_admin() ) {
		foreach ($ads as $paragraph_id => $ad_code) {
			$content = prefix_insert_after_paragraph( $ad_code, $paragraph_id, $content );
		}
	}
	return $content;
}

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 );
}
section

如果只显示在某个分类文章中添加,也可以这么写

add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
	$ad_code = '<div>自定义文字</div>';
		if ( is_single() && ! is_admin() && in_category('29') ) {
		return prefix_insert_after_paragraph( $ad_code, $content );
	}
	return $content;
}


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 );
}

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
评论  6  访客  4  作者  2
    • 网友
      网友 2

      在文章最后添加小工具,而不是段落2,应该怎么改

        • 知更鸟
          知更鸟

          @ 网友 https://zmingcx.com/add-widgets-to-wordpress-posts.html

        • 懒死我了.
          懒死我了. 0

          每个段落都添加怎么实现

        匿名

        发表评论

        匿名网友
        :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

        拖动滑块以完成验证