Skip to content

Instantly share code, notes, and snippets.

@vaakash
Created February 7, 2024 18:17
Show Gist options
  • Save vaakash/9ef63c22192316b81986a4d78192b39f to your computer and use it in GitHub Desktop.
Save vaakash/9ef63c22192316b81986a4d78192b39f to your computer and use it in GitHub Desktop.
Adding ID to headings in WordPress
<?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