# 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.

- Type: PHP
- Runs: Frontend only
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: headings, anchors, links
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/heading-anchor-links/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Copyable Anchor Links on Headings" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
