Created
January 3, 2025 09:49
-
-
Save audrasjb/430a2b44c82b4f34063c70754009f132 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* 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