Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.