在 WordPress 文章正文开头和末尾分别添加固定内容

WordPress31.1K阅读模式

在不修改主题正文模板文件的情况下,想在正文开头和末尾添加固定内容,或者在已发表的文章中添加固定内容又不想重新编辑文章,可以通过下面的代码实现。

在 WordPress 文章正文开头和末尾分别添加固定内容

在正文开头和末尾分别添加固定内容

会用到过滤器钩子add_filter:

add_filter( 'the_content', '' )

将下面代码添加到当前主题函数模板functions.php中。

在文章内容开头添加固定内容

add_filter('the_content', 'add_zm_content_beforde');
function add_zm_content_beforde( $content ) {
	if( !is_feed() && !is_home() && is_singular() && is_main_query() ) {
		$before_content = '在文章内容开头添加固定内容';
		$zm = $before_content . $content;
	}
	return $zm;
}

在文章内容末尾添加固定内容

add_filter('the_content', 'add_zm_content_after');
function add_zm_content_after( $content ) {
	if( !is_feed() && !is_home() && is_singular() && is_main_query() ) {
		$after_content = '在文章内容末尾添加固定内容'; 
		$zm = $content . $after_content;
	}
	return $zm;
}

同时在开头和末尾添加固定内容

add_filter('the_content', 'add_zm_content_before_and_after');
function add_zm_content_before_and_after( $content ) {
	if( !is_feed() && !is_home() && is_singular() && is_main_query() ) {
		$after_content = '在文章内容末尾添加固定内容'; 
		$before_content = '在文章内容开头添加固定内容';
		$zm = $before_content . $content . $after_content;
	}
	return $zm;
}

只在自定义文章类型“books”文章末尾添加固定内容

add_filter('the_content', 'add_zm_content_after_books_custom_post_type');
function add_zm_content_after_books_custom_post_type( $content ) {
	if (is_singular( "books" )){
		$new_books_content = '只在自定义帖子类型“books”文章末尾添加固定内容';
		$aftercontent = $new_books_content;
		$zm = $content . $aftercontent;
		return $zm;
	} else {
		return $content;
	}
}

这是个经常用到的功能。

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

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
评论  3  访客  3
    • 奶爸建网站笔记
      奶爸建网站笔记 4

      学习一下,现在用的主题自带hooks入口,可以自己加内容,所以用不到自己改代码了:mrgreen:

      • zero
        zero 1

        学习一下

        • 明月登楼
          明月登楼 2

          不错,终于找到自定义类型的了,赞一个!

        匿名

        发表评论

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

        拖动滑块以完成验证