WordPress 文章生成目录索引

WordPress1 1.6K阅读模式

WordPress文章目录索引,可以方便浏览者阅读,文本分享一段最新免插件生成WordPress 文章目录索引代码,可以将h2-h6段落标题自动生成文章生成目录索引,并可实现分层级。

WordPress 文章生成目录索引

WordPress 文章生成目录索引

section

最新代码版

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

// declare a function and pass the $content as an argument
function insert_table_of_contents($content) {
	// used to determine the location of the
	// table of contents when $fixed_location is set to false
	$html_comment = "<!--insert-toc-->";
	// checks if $html_comment exists in $content
	$comment_found = strpos($content, $html_comment) ? true : false;
	// set to true to insert the table of contents in a fixed location
	// set to false to replace $html_comment with $table_of_contents
	$fixed_location = true;

	// return the $content if
	// $comment_found and $fixed_location are false
	if (!$fixed_location && !$comment_found) {
		return $content;
	}

	// 设置排除,默认页面文章不生成目录
	// exclude the table of contents from all pages
	// other exclusion options include:
	// in_category($id)
	// has_term($term_name)
	// is_single($array)
	// is_author($id)
    if (is_page()) {
        return $content;
    }
		
	// regex to match all HTML heading elements 2-6
	$regex = "~(<h([2-6]))(.*?>(.*)<\/h[2-6]>)~";

	// preg_match_all() searches the $content using $regex patterns and
	// returns the results to $heading_results[]
	//
	// $heading_results[0][] contains all matches in full
	// $heading_results[1][] contains '<h2-6'
	// $heading_results[2][] contains '2-6'
	// $heading_results[3][] contains '>heading title</h2-6>
	// $heading_results[4][] contains the title text
	preg_match_all($regex, $content, $heading_results);

	// 默认小于3个段落标题不生成目录
	// return $content if less than 3 heading exist in the $content
	$num_match = count($heading_results[0]);
	if($num_match < 3) {
		return $content;
	}

	// declare local variable
	$link_list = "";
	// loop through $heading_results
	for ($i = 0; $i < $num_match; ++ $i) {

	    // rebuild heading elements to have anchors
	    $new_heading = $heading_results[1][$i] . " id='$i' " . $heading_results[3][$i];

	    // find original heading elements that don't have anchors
	    $old_heading = $heading_results[0][$i];

	    // search the $content for $old_heading and replace with $new_heading
		$content = str_replace($old_heading, $new_heading, $content);

	    // generate links for each heading element
	    // each link points to an anchor
	    $link_list .= "<li class='heading-level-" . $heading_results[2][$i] .
	    	"'><a href='#$i'>" . $heading_results[4][$i] . "</a></li>";
	}
	    
	// opening nav tag
	$start_nav = "<nav class='table-of-content'>";
	// closing nav tag
	$end_nav = "</nav>";
	// title
	$title = "<h2>Table of Contents</h2>";

	// wrap links in '<ul>' element
	$link_list = "<ul>" . $link_list . "</ul>";

	// piece together the table of contents
	$table_of_contents = $start_nav . $title . $link_list . $end_nav;

	// if $fixed_location is true and
	// $comment_found is false
	// insert the table of contents at a fixed location
	if($fixed_location && !$comment_found) {
		// location of first paragraph
		$first_paragraph = strpos($content, '</p>', 0) + 4;
		// location of second paragraph
		$second_paragraph = strpos($content, '</p>', $first_p_pos);
		// insert $table_of_contents after $second_paragraph
		return substr_replace($content, $table_of_contents, $second_paragraph + 4 , 0);
	}
	// if $fixed_location is false and
	// $comment_found is true
	else {
		// replace $html_comment with the $table_of_contents
		return str_replace($html_comment, $table_of_contents, $content);
	}
}
// pass the function to the content add_filter hook
add_filter('the_content', 'insert_table_of_contents');

默认页面和文章中少于三个段落标题不生成目录,代码中加了中文注释,可酌情修改。

section
层级显示

可以通过调整样式显示层级关系

例如:H3为一级,H4、H5、H6为二级

.heading-level-4,
.heading-level-5,
.heading-level-6 {
	margin-left: 40px;
}

效果参考文本目录。

section
jQuery平滑滚动代码

需要加载jQuery.js

jQuery(document).ready(function($){
	$('.table-of-content a[href*=#]').click(function() {
		if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
			var $target = $(this.hash);
			$target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
			if ($target.length) {
				var targetOffset = $target.offset().top;
				$('html,body').animate({
					scrollTop: targetOffset - 100
				},
				800);
				return false;
			}
		}
	});
})

其中:scrollTop: targetOffset - 100,为距上100px,用于固定的导航菜单。

想实现显示当前目录位置考虑使用 js-toc,利用JQ将目录提取出来,可以实时显示当前滑动位置所在的目录,但不能实现层级显示。

section

目录生成插件

代码版适合有一定动手能力的用户,即想省力,又想有更多的设置选择,可以使用下面推荐的一堆目录生成插件。

使用比较多的目录插件

Easy Table of Contents

可以使用短代码在文章任意位置添加目录

Table of Contents Plus

有目录索引小工具,可以添加到侧边栏小工具中。

上述两款插件后台功能设置极其相似,都有完整的中文语言包。

section
其它目录生成插件

WP后台→插件→安装插件,搜索安装。

  • Ultimate Blocks
  • CM Table Of Contents
  • Multipage
  • Shortcode Table of Contents
  • LuckyWP Table Of Contents

 

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

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
    • 法大师傅
      法大师傅 0

      范德萨发

    匿名

    发表评论

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

    拖动滑块以完成验证