Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -230,3 +230,22 @@ function redirect_private_pages_to_join_page() {
}

add_action( 'template_redirect', __NAMESPACE__ . '\\redirect_private_pages_to_join_page' );

/**
* Add id attribute to <h1>, <h2>, <h3>, <h4>, <h5> tags
*
* @param string $content Content of the current post.
*
* @return string $content The filtered post content.
*/
function anchor_content_headings( $content ) {
$content = preg_replace_callback( "/\<h([1|2|3|4|5])\>(.*?)\<\/h([1|2|3|4|5])\>/", function ( $matches ) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no guard to prevent this matching a heading which already contains linked text, and a link cannot appear inside a link so one of them would break.

$hTag = $matches[1];
$title = $matches[2];
$slug = sanitize_title_with_dashes( $title );
return '<a href="#'. $slug .'"><h'. $hTag .' id="' . $slug . '">' . $title . '</h'. $hTag .'></a>';
}, $content );

return $content;
}
add_filter( 'the_content', __NAMESPACE__ . '\\anchor_content_headings' );