Give every heading in your posts an id and a small "#" link, so readers can share links to a specific section.
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 );
} );
} );
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.
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.
Open a long post and hover over a heading. A faint # should appear; clicking it should add #section-name to the URL.