Copyable Anchor Links on Headings
Gives h2 to h4 headings in posts and pages an ID and a small # link that appears on hover, so readers can share a link to an exact section.
Opens WPIDE on
Code
add_filter( 'the_content', function ( $content ) {
if ( ! is_singular() || ! in_the_loop() || ! is_main_query() ) {
return $content;
}
$used = array();
$result = preg_replace_callback( '/<h([2-4])([^>]*)>(.*?)<\/h\1>/is', function ( $m ) use ( &$used ) {
$attrs = $m[2];
if ( preg_match( '/\sid=["\']([^"\']+)["\']/i', $attrs, $id_match ) ) {
$id = $id_match[1];
} else {
$base = sanitize_title( wp_strip_all_tags( $m[3] ) );
$base = '' !== $base ? $base : 'section';
$id = $base;
$i = 2;
while ( isset( $used[ $id ] ) ) {
$id = $base . '-' . $i++;
}
$attrs .= ' id="' . esc_attr( $id ) . '"';
}
$used[ $id ] = true;
return '<h' . $m[1] . $attrs . '>' . $m[3] . ' <a class="wpide-heading-anchor" href="#' . esc_attr( $id ) . '" aria-label="Link to this section">#</a></h' . $m[1] . '>';
}, $content );
return null === $result ? $content : $result;
}, 25 );
add_action( 'wp_head', function () {
echo '<style>.wpide-heading-anchor{margin-left:.3em;font-weight:400;text-decoration:none;opacity:0;transition:opacity .15s}h2:hover>.wpide-heading-anchor,h3:hover>.wpide-heading-anchor,h4:hover>.wpide-heading-anchor,.wpide-heading-anchor:focus{opacity:.6}</style>' . "\n";
} );
Notes
Works alongside the table of contents snippet; headings that already have an ID keep it.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.