Generate a Table of Contents for Your WordPress Post with PHP

In this tutorial, we will explore the creation of a custom PHP script for a WordPress website. The goal is to offer students and beginners a reference or guide to enhance their knowledge and skills in developing custom PHP scripts within WordPress. I'll be providing a simple snippet that generates an automated Table of Contents for post content.

What is the Purpose of Table of Contents in Website Content?

The purpose of a Table of Contents (TOC) in website content is to offer users a structured and organized navigation tool. It enhances website usability, facilitates navigation, and contributes to an improved overall user experience. This is particularly valuable for content-rich websites or lengthy articles.

How to Create an Auto-generated Table of Contents (TOC) in WordPress?

Below, I will provide a sample PHP script demonstrating an Auto-generated Table of Contents (TOC). Follow the steps outlined below:

Step 1: Add Custom Style

In your WordPress site theme, integrate the following Cascading Style Sheet (CSS) script below. This style defines the custom design for the Table of Contents.

  1. .custom-toc-container {
  2. display: block;
  3. width: 100%;
  4. padding: 0.75em 1em;
  5. border: 1px solid #00000024;
  6. box-shadow: 2px 5px 5px #00000024;
  7. margin-bottom: 15px;
  8. border-radius: 7px;
  9. }
  10. .custom-toc-title {
  11. font-size: 1.5rem;
  12. letter-spacing: .8px;
  13. font-weight: 600;
  14. border-bottom: 1px solid #d3c9c9;
  15. padding-bottom: 10px;
  16. margin-bottom: 15px;
  17. }
  18. ul.custom-toc .custom-toc-item {
  19. padding: 3px 1px;
  20. list-style: square;
  21. }
  22. a.custom-toc-item {
  23. font-weight: 500;
  24. text-decoration: none;
  25. }

Step 2: Add Custom PHP Script

WordPress provides a highly useful built-in filter hook called `the_content`. Utilizing this filter, we can modify the post content in WordPress before rendering it on the front end. To achieve this, open the `functions.php` file of your active WP Theme and add the custom PHP script with the mentioned filter, as shown below:

  1. <?php
  2. /**
  3.  * Generate Table of Contents
  4.  */
  5. function custom_content_toc($content){
  6. $new_content = $content;
  7. if(is_single()){
  8. $list = [];
  9. $ids = [];
  10. // Find all Headings from Content
  11. $headings = preg_match_all('/<h\d[^>]*>.*?<\/h\d>/si', $content, $matches);
  12. if($headings > 0 && isset($matches[0])){
  13. foreach($matches[0] as $k => $heading){
  14. // Getting the Heading Level
  15. preg_match_all('/<h(\d)[^>]*>/si', $heading, $level);
  16. $level = $level[1][0] ?? 1;
  17.  
  18. //update heading attributes
  19. $id = "";
  20. $dom = new DOMDocument();
  21. $dom->loadHTML($heading);
  22. $html = new DOMXPath($dom);
  23. foreach($html->query('//h1 | //h2 | //h3 | //h4 | //h5') as $el){
  24. // Get Heading ID
  25. $id= $el->getAttribute('id') ?? '';
  26. // Generate Heading ID if not exists
  27. if(empty($id)){
  28. $id = str_replace([" ",".",","], "-",trim(strtolower(strip_tags($heading))));
  29. }
  30. $i=1;
  31. while(true){
  32. if(!in_array($id, $ids)){
  33. $ids[] = $id;
  34. break;
  35. }else{
  36. $id = $id."_".($i++);
  37. }
  38. }
  39. // Set Heading's Updated ID attribute
  40. $el->setAttribute('id', $id);
  41. }
  42. $new_heading = $dom->saveHTML();
  43. $new_content = str_replace($heading, $new_heading, $new_content);
  44.  
  45. $parent = false;
  46. // Locate and set the parent Heading
  47. if($level > 1 && !empty($list)){
  48. $headingBeforeArr = array_slice($list, 0, $k + 1);
  49. krsort($headingBeforeArr);
  50. foreach($headingBeforeArr as $key => $headingBefore){
  51. if($headingBefore['level'] < $level){
  52. $parent = $key;
  53. break;
  54. }
  55. }
  56. }
  57. // Add heading Item to array
  58. $list[] = ["level" => $level, "html" => $heading, "parent" => $parent, "id" => $id];
  59. }
  60. }
  61.  
  62. /**
  63.   * Generate the Table of Content
  64.   */
  65. $toc = "";
  66. if(!empty($list)){
  67. $toc .= "<div class='custom-toc-container'>";
  68. $toc .= "<div class='custom-toc-title'>Table of Contents</div>";
  69. $toc .= "<ul class='custom-toc'>";
  70. foreach($list as $k=> $row){
  71. if($row['parent'] !== false)
  72. continue;
  73. $toc .= "<li class='custom-toc-item'>";
  74. $toc .= "<a href ='#{$row['id']}' class='custom-toc-item'>".(strip_tags($row['html']))."</a>";
  75. // Find Child Headings
  76. $toc .= get_child($list, $k);
  77. $toc .= "</li>";
  78. }
  79. $toc .= "</ul>";
  80. $toc .= "</div>";
  81. }
  82.  
  83. }
  84. // Return Post Content with Table of Contents
  85. $new_content = $toc. $new_content;
  86. return $new_content;
  87. }
  88.  
  89. /**
  90.  * Generate Sub-Headings for Table of Contents
  91.  */
  92. function get_child($list = [], $parent = null){
  93. $child_content = "";
  94. if(!empty($list) && !is_null($parent)){
  95. foreach($list as $k => $row){
  96. if(!is_numeric($row['parent']) || $row['parent'] != $parent)
  97. continue;
  98. $child_content .= "<li class='custom-toc-item'>";
  99. $child_content .= "<a href ='#{$row['id']}' class='custom-toc-item'>".(strip_tags($row['html']))."</a>";
  100. $child_content .= get_child($list, $k);
  101. $child_content .= "</li>";
  102. }
  103. }
  104. if(!empty($child_content))
  105. $child_content = "<ul class='custom-toc'>{$child_content}</ul>";
  106. return $child_content;
  107. }
  108.  
  109. add_filter( 'the_content' , 'custom_content_toc', 10, 1);
  110. ?>

Snapshots

Below are example snapshots utilizing the Custom CSS and PHP Script provided above to generate the Table of Contents for WordPress Posts:

WP Post without Table of Content

WordPress Table of Contents using Custom PHP Script

Table of Content UI

WordPress Table of Contents using Custom PHP Script

WP Post with Table of Content

WordPress Table of Contents using Custom PHP Script

There you have it! I trust that this Generate a Table of Contents for Your WordPress Post with PHP Tutorial proves beneficial for your needs and provides valuable insights for your future WordPress Website. Dive into more on this website for an array of Tutorials, Free Source Codes, and Articles covering various programming languages.

Consider exploring the following articles as well:

Happy Coding =)

Add new comment