Skip to content

Instantly share code, notes, and snippets.

@JeroenSormani
Created July 17, 2015 11:13
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JeroenSormani/9e5e4215e6fd8ab281c9 to your computer and use it in GitHub Desktop.
Save JeroenSormani/9e5e4215e6fd8ab281c9 to your computer and use it in GitHub Desktop.
WordPress auto add IDs to headings
<?php
/**
* Automatically add IDs to headings such as <h2></h2>
*/
function auto_id_headings( $content ) {
$content = preg_replace_callback( '/(\<h[1-6](.*?))\>(.*)(<\/h[1-6]>)/i', function( $matches ) {
if ( ! stripos( $matches[0], 'id=' ) ) :
$matches[0] = $matches[1] . $matches[2] . ' id="' . sanitize_title( $matches[3] ) . '">' . $matches[3] . $matches[4];
endif;
return $matches[0];
}, $content );
return $content;
}
add_filter( 'the_content', 'auto_id_headings' );
@wpsumo
Copy link

wpsumo commented Oct 25, 2023

@JeroenSormani In 2023 where emojis are popular to use in headlines, we need to filter and remove emojis from added to the ID as it breaks the function of anchor link when there is an emoji in the ID.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment