/**
 * Find all headings in the page content and inject them with anchor link.
 *
 * @param string $content page content.
 *
 * @return string
 */
function dorzki_generate_titles_anchros_links( $content ) {

	return preg_replace_callback( '/<(h[1-6])>(.*?)<\/h[1-6]>/i', 'dorzki_inject_titles_anchor_link', $content );

}

add_filter( 'the_content', 'dorzki_generate_titles_anchros_links' );


/**
 * Replace the heading with a heading and anchor link.
 *
 * @param array $match math result array.
 *
 * @return string
 */
function dorzki_inject_titles_anchor_link( $match ) {

	return sprintf( '<%1$s><a class="title-anchor-link" id="%2$s" href="#%2$s"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"/><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"/></svg></a>%3$s</%1$s>', $match[1], sanitize_title( $match[2] ), $match[2] );

}

Credit: dorzki.co.il

How to use it?

Usually adding functionality to a WordPress site is by creating a plugin.
However you can simply copy the code and paste it in your child theme’s functions.php file at the end of the file, just before ?>.

For JavaScript code you will need to add them to your theme’s main JavaScript file.

Having issues with the code?

If the code doesn’t work or you get an error please let us know in the comments section.
We will do our best to fix it as-soon-as-possible and update the code on this page.

Comments

  1. DOM

    This is very useful, mostly on pages with long content like documentation.

    Thank you!

    Reply

Leave a Reply