A content table is what you can use in some big and small documents to reference all the titles so as to give quick access to certain part of the document.
You see that often on FAQs pages for example or other long page where inner navigation is needed.
The point here is to automate the process of creating a content table in WordPress. We are going to produce a list of a certain type of headers at the top of the page/post and link them with anchors to the document. Something similar to this:
Sounds good but there is a limitation. We are not going to support nested titles list for now. It is possible but it would make the code much more complex.
The code is pretty simple and will consist of one function hooked to the filter “the_content” available in WordPress. Using a shortcode like content_table tag=”h2″ between  will tell the function to generate the table.
Let’s get started
Here is the full code. I’ll go in more details below.
So, what have we got there.
The function add_filter is a built function in WordPress which link functions to a particular trigger. In this case we use the filter the_content, which is called just before WordPress prints out the content of a post/page. The filter will pass the content of the post/page to each functions hooked to it. Now all we need is work on the content using the function get_content_table we’ve just hooked.
The get_content_table function.
First we need to find out if the content table is requested so we search for the string content_table (parameters) (between ). If we find one then we carry on, if not we just return the content untouched.
If the shortcode is there we need to get which tag needs to be used to build the table. WordPress provides a function to do that in the shortcode api. Once we have the targeted tag we can do a search for it in the content and put the results in an array.
Now the interesting stuff:
If the right type of titles are present then we start building the content_table. First we find out how many elements we’ve got then create a div container to hold everything and start the first unordered list.
When we reach half of the elements we close the first ul and open a new one to create to list. This will help if you want to split the content table in two columns. Note: we have to slug the titles to use them as anchor links and keep the code valid.
The next is to add the back to top link to the existing titles:
We use the power of regular expressions and callback function to get that sorted. I think this was the trickiest bit of the code.
If you place this code in you function folder and add a the content_table tag=”X” (between , don’t forget the double quotes around the tag) shortcode (where X is the tag used for your titles) then you should get a nice content table where you have added the shortcode. Add some simple styling and you’re done!