Add IDs to all headings on a page in WordPress

See how to set the ID attribute for a heading, based on the heading content.

September 2, 2023 wordpressphpgutenberg

Add a ID attribute for all heading

1
<?php
2
add_filter('the_content', 'add_id_attribute_to_headings');
3
4
function add_id_attribute_to_headings($content): string {
5
return preg_replace_callback('#<(h[1-6])(.*?)>(.*?)</(h[1-6])>#', 'add_id_attribute_to_heading_callback', $content);
6
}
7
8
function add_id_attribute_to_heading_callback($match): string {
9
[$full, $el_start, $attributes, $content, $el_end] = $match;
10
11
if (str_contains($full, ' id="')) {
12
return $full;
13
}
14
15
$id = sanitize_title_with_dashes($content);
16
return '<{$el_start} id="{$id}" {$attributes}>{$content}</{$el_end}>';
17
}

Do you like the content?

Your support helps me continue my work. Please consider making a donation.

Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are accepted.

Leave a comment