Adding Anchor Tags to Subheadlines in WordPress

If you want to have clickable subheadlines with auto scroll function on your WordPress blog you could do following. There are some plugins doing the same and much more but I thought they are kinda oversized. The little piece of code below does the trick.

In admin panel go to Appearance > Editor > Theme Functions (functions.php). Insert anywhere:

function add_content_filter_headline_anchor($content) {
    if (is_single() && !is_null($content)) {
        $content = preg_replace_callback('~(<h[2-6].*)>(.*)(</h[2-6]>)~i', function ($matches) {
            $title = $matches[2];
            $slug = sanitize_title_with_dashes($title);
            return $matches[1] . ' id="' . $slug . '"><a href="#' . $slug . '">' . $title . '</a>' . $matches[3];
        }, $content);
    return $content;
add_filter('the_content', 'add_content_filter_headline_anchor');

Go to Appearance > Customize > Custom CSS. Insert anywhere:

h2 a, h3 a, h4 a, h5 a, h6 a {
    text-decoration: none;

h2 a:hover, h3 a:hover, h4 a:hover, h5 a:hover, h6 a:hover {
    text-decoration: underline;
} a {
    text-decoration: none;