Created
February 7, 2024 18:17
-
-
Save vaakash/9ef63c22192316b81986a4d78192b39f to your computer and use it in GitHub Desktop.
Adding ID to headings in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Adds "id" attribute to heading tags in WordPress post content using the "the_content" filter and regex. | |
*/ | |
function anchor_headings( $content ) { | |
$content = preg_replace_callback( '/(\<h[2-3](.*?))\>(.*)(<\/h[2-3]>)/i', function( $matches ) { | |
if ( ! stripos( $matches[0], 'id=' ) ){ | |
$slug = sanitize_title( $matches[3] ); | |
$matches[0] = $matches[1] . $matches[2] . ' id="' . $slug . '">' . $matches[3] . ' <a href="#' . $slug . '" aria-hidden="true" class="anchor">#</a>' . $matches[4]; | |
} | |
return $matches[0]; | |
}, $content ); | |
return $content; | |
} | |
add_filter( 'the_content', 'anchor_headings' ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment