At this point I’m starting to write more and more blog posts. Every now and then I get a couple questions from people that I’ve covered in a blog post before and I will send them a link to that blog post. This works great, but can be a bit lacking if you want to specifically point to a section in that post.
For those who are less familiar with HTML, you can assign an id to each HTML tag like this
<h1 id='hello-world'>Hello World</h1>. When doing that, you can actually send someone a link like this; http://domain.com/post-url#hello-world (note the
# in front of the ID). What will happen is that the user who will click on that link, will be directly taken to the section with that specific
Adding a ID to each heading (or section) can be a big pain and you don’t want to do that, you want to write!
Automatically adding IDs
The solution here would to automatically add IDs to each heading in your post. To accomplish this, I’ve created a code snippet that can be used accomplish this. You can copy/paste the code below in your themes functions.php and it will automatically add the IDs. When you’ve already assigned an ID to the heading it will not do anything to it.
The ID that is assigned to the HTML tag is the title text, only then all lowercase, without HTML tags, and without spaces.
This code can be used by anyone, even if you don’t intent use it yourself, you will most likely make someone very happy that does want to use it! Visually there won’t change a thing so there is very little reason not to use it.
The result of the code above:
Adding anchors in front of the titles
If you want to take it a step further, you can also add anchor icons in front of your heading and link that to that specific section.
This way you will make it almost too easy to share a section of your post, and people will love it!
In order to get this done you can use the modified code below. Do note that you do need a anchor icon somewhere. I’m using
<i class="glyphicon glyphicon-link"></i> to display my icon, mine is a Twitter Bootstrap icon (see what I did with that link, its a link to the icons section!).
This also needs a little bit of CSS:
Hiding the anchor icon
Ok, so I know some people will not dig the new icon next to their headings. It is also possible to hide the anchor until someone hovers over the heading. Only change would be a bit CSS change.
This is a very simple feature, but can be very powerful for your website visitors. Please leave a comment below if this was helpful for you, or if you ran into any challenges 🙂