Theme & Front End JavaScript Intermediate

Add Link Anchors to Headings

Give every heading in your posts an id and a small "#" link, so readers can share links to a specific section.

Tested on WordPress 7.1 No plugin needed Updated
script.js 26 lines
document.addEventListener( 'DOMContentLoaded', () => {
	const content = document.querySelector( '.entry-content, .wp-block-post-content' );
	if ( ! content ) {
		return;
	}

	content.querySelectorAll( 'h2, h3' ).forEach( ( heading ) => {
		if ( ! heading.id ) {
			const base = heading.textContent.trim().toLowerCase().replace( /[^\p{L}\p{N}]+/gu, '-' ).replace( /^-+|-+$/g, '' ) || 'section';
			let id = base;
			let n = 2;
			while ( document.getElementById( id ) ) {
				id = base + '-' + n++;
			}
			heading.id = id;
		}

		const link = document.createElement( 'a' );
		link.href = '#' + heading.id;
		link.className = 'nahnu-anchor';
		link.setAttribute( 'aria-label', 'Link to "' + heading.textContent.trim() + '"' );
		link.textContent = '#';
		link.style.cssText = 'margin-left:.35em;opacity:.4;text-decoration:none';
		heading.appendChild( link );
	} );
} );

Where to add this

Recommended A code snippets plugin As a JavaScript snippet set to load in the footer.
Child theme Save it as a .js file and load it with wp_enqueue_script() from functions.php.
Page builder Your builder's custom code area, set to load in the footer.

Long guides are easier to share and reference when each section has its own link. This script gives every H2 and H3 an anchor, like documentation sites do.

How it works

The script looks inside your post content (.entry-content in classic themes, .wp-block-post-content in block themes). Headings without an id get one made from their text, such as “how-it-works”, with a number added if that id is already used. Letters in any language are kept.

A faint “#” link is then added after each heading. Clicking it updates the address bar, so the reader can copy and share a link straight to that section.

Things to watch

  • Ids are added in the browser, so links to them only work once the page has loaded. If you need ids in the HTML for search engines, add them in the editor under each heading’s Advanced → HTML anchor.
  • Combine with the snippet that offsets anchor targets if you have a sticky header.

How to test it

Open a long post and hover over a heading. A faint # should appear; clicking it should add #section-name to the URL.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only