WordPress: Automatically add IDs to headings such as <h2>

<?php function auto_id_headings( $content ) { $content = preg_replace_callback( '/(\<h[1-6](.*?))\>(.*)(<\/h[1-6]>)/i', function( $matches ) { if ( ! stripos( $matches[0], 'id=' ) ) : $heading_link = '<a href="#' . sanitize_title( $matches[3] ) . '" class="heading-link"><span class="dashicons dashicons-admin-links"></span></a>'; $matches[0] = $matches[1] . $matches[2] . ' id="' . sanitize_title( $matches[3] ) . '">' . $heading_link . $matches[3] . $matches[4]; endif; return $matches[0]; }, $content ); return $content; } add_filter( 'the_content', 'auto_id_headings' ); ?>
Simply paste this code snippet in the functions.php file of your (child) theme (without the php tags).

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.