PHP snippet · Content & Text
Table of contents shortcode
A shortcode that builds a linked table of contents from the headings in a post, adding the anchor ids for you and indenting by level.
About this php snippet
Place the shortcode anywhere in the post content and it prints a list of the headings on the page, each one linked to the right place. Heading ids are added for you, so there is nothing to prepare and nothing to maintain as the post grows.
Usage
- [emcp_toc]
- [emcp_toc title="On this page" levels="2,3"]
- [emcp_toc title=""] for the list with no heading above it
What it does
- Collects the H2, H3, and H4 headings from the rendered post content
- Adds an id to each heading so the links have somewhere to land
- Prints a nested list, indented by heading level, wrapped in a labelled nav element for screen readers
- Brings its own small stylesheet, printed once, that you can restyle or replace
Good to know
- The list is not built by re-reading the raw post. One pass walks the rendered HTML, assigns the ids and records what it found, and the shortcode then prints exactly that record. Both halves see identical markup, so a link can never point at an id that was never written.
- An id you set on a heading yourself is kept, so anchors you have already shared stay valid
- Two headings with the same wording get separate anchors, so the second link does not land on the first
- A post with no headings prints nothing at all, rather than an empty box
- Elementor keeps its layout in post meta rather than post content, so headings built with Elementor widgets are not visible to it. Classic and Gutenberg posts are fully covered.



