想要在每篇文章中加入固定内容,需要修改主题下functions.php文件,加入如下内容。
/* ** 为WordPress,每篇文章中加入自定义内容模板。此处是顶部和尾部 */ //需要特别设置的分类目录 $special_category_array = array('分类目录1','分类目录2'); //工具方法,获取顶级父分类目录 function get_category_root_name($cat){ $this_category = get_category($cat); // 取得当前分类 while($this_category->category_parent) // 若当前分类有上级分类时,循环 { $this_category = get_category($this_category->category_parent); // 将当前分类设为上级分类(往 } return get_cat_name($this_category->term_id); // 通过该分类的id号返回名称 } //添加顶部SEO的各种内链接 function add_seo_links_on_post_top( $content ) { global $special_category_array; $top_add_content = ''; if(!is_feed() && !is_home() && is_singular() && is_main_query()) { $category = get_the_category(); if(in_array($category[0]->cat_name, $special_category_array, true) ){ // 使用当前分类目录名称 $this_category_name = $category[0]->cat_name; }else{ // 去查其根分类名称 $this_category_name = get_category_root_name($category[0]->cat_ID); } switch ($this_category_name) { case '分类目录1': $top_add_content = 's1'; break; case '分类目录2': $top_add_content = 's2'; break; case '分类目录3': $top_add_content = 's3'; break; } //插入顶部的写法 $content = $top_add_content.$content; } return $content; } add_filter('the_content', 'add_seo_links_on_post_top'); //添加尾部,原文链接 function add_origin_link_on_post_end($content) { if(!is_feed() && !is_home() && is_singular() && is_main_query()) { $title = get_the_title(); $permalink = get_permalink(); $custom_header_content = '<p class="article-copyright">原文链接:<a href="' .$permalink. '" title="' .$title. '">' .$title. '</a></p>'; //插入尾部的写法 $content .= $custom_header_content; } return $content; } add_filter('the_content', 'add_origin_link_on_post_end');
实例代码