Skip to content

Instantly share code, notes, and snippets.

@audrasjb
Created January 3, 2025 09:49
Show Gist options
  • Save audrasjb/430a2b44c82b4f34063c70754009f132 to your computer and use it in GitHub Desktop.
Save audrasjb/430a2b44c82b4f34063c70754009f132 to your computer and use it in GitHub Desktop.
/**
* Filters the_content to automatically add unique ID to headings.
*
* Note: Change the regex to modify the related heading levels.
* Defaults to levels 2 and 3.
*/
function who_automatic_heading_ids( $content ) {
$pattern = "~<h(2|3)[^>]*>(.*?)</h(2|3)>~";
$content = preg_replace_callback( $pattern, function ( $matches ) {
$title = $matches[2];
$slug = sanitize_title_with_dashes( $title ) . '-' . uniqid();
return "<h{$matches[1]} class='wp-block-heading' id='" . $slug . "'>" . $title . "</h{$matches[1]}>";
}, $content );
return $content;
}
add_filter( 'the_content', 'who_automatic_heading_ids' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment