Header Anchors,Anchors for WordPress,WordPress

Automatic Header Anchors for WordPress Without Plugin

Header Anchors for WordPress with only 3 lines of JS and No plugin?? Yes It’s so easy to set up… Thank you IT Cooking! The JS requires your headers to have an ID, and what better then a Table Of Content plugin to have them for free!

Header Anchors for WordPress Step by Step Process


Required: A Snippet loader: we recommend Simple Custom CSS & JS

Simple Custom CSS and JS banner

Optional: A table of content plugin: we recommend TOP Table Of Contents

banner top toc

The JS snippet provided also adds ids to your headers…

Add this JS Snippet to Attach an Anchor to Headers

window.addEventListener("load", function(){
  // Loop through all your headers inside article section only
  // Headers shall be there thanks to TOC plugin, if not we just add them
  // AddOnly h2 and h3, add the headers you want
  $("article").find("h2, h3").each(function() {
    if (!this.id) {
      let id = this.textContent.replace(/[^a-zA-Z0-9]+/g, "-").toLowerCase();
      this.setAttribute('id', id);
    $(this).append('<a class="anchor" href="#'+this.id+'"></a>');  // anchors after
    //$(this).prepend('<a class="anchor" href="#'+this.id+'"></a>'); // anchors before

The JS appends/prepends a link with class .anchor to every h2/h3 found on the page, that have an id or not. Will add ids if missing. It does NOT add links to headers outside the article content (read more, etc).

Add this CSS to Format the Anchors

.anchor {
  visibility: hidden;
  text-decoration: none !important;
/* add more levels if you need */
h3:hover > .anchor, 
h2:hover > .anchor {
  visibility: visible;
.anchor::before { 
  content: "🔗";

Anchor is visible on hover, right side, and is an emoji. You can replace the emoji by an <i> from fontawesome if you like.


css js snippets to add anchor to headers


Leave a Reply

Your email address will not be published. Required fields are marked *