Automatically Create an Anchor Menu from Heading Tags in PHP
I updated the design of my blog today, and I wanted to add an anchor menu so my users could jump to each section of long blog posts with ease. I started out with a jQuery function that automatically created the anchor menu by looping though each heading and then adding an ID to each H3 title and finally outputting a menu. This worked pretty well, but it wasn't good enough for me. I wanted it to be SEO friendly, so I decided to write it in PHP.
Here is an example of this function being used on a blog post that has many H3 Tags just like the menu you see in the right menu of this page:
The Problem
The biggest problem is I didn't want to have to go in and add IDs to each H3 tag, so I automated that process, by using PHPs DOMDocument(). It made things pretty simple.
The Solution to Creating an Automated Anchor Menu in PHP
The process starts before you submit your blot post, or whatever you want to create a anchor menu from, the function takes that text and then does the following:
- Find all the H3 tags and store the text between each tag.
- Format the H3 title text so it can be used as an ID anchor tag & in the URL
- Add the newly created ID to the H3 Tag as well as store a list of URLs with the corresponding URL and Title text.
- Save the new post data
- Either save the Menu links to the database or you can output on them when you display the post.
Add New Comment