Skip to content

Instantly share code, notes, and snippets.

@bigsweater
Created June 18, 2016 21:35
Show Gist options
  • Save bigsweater/39358aca10f1156a910354893ba7558c to your computer and use it in GitHub Desktop.
Save bigsweater/39358aca10f1156a910354893ba7558c to your computer and use it in GitHub Desktop.
Function to add IDs to heading tags in WordPress (without regex) using PHP DOMDocument
<?php
// Obviously remove namespace stuff if you're not using namespaces.
/**
* Add anchor IDs to headings in content
*/
function anchor_headings( $content ) {
$charset = '';
if ( defined('DB_CHARSET') ) {
$charset = DB_CHARSET;
} else {
$charset = 'UTF-8';
}
$doc = new \DOMDocument();
$doc -> LoadHTML( mb_convert_encoding($content, 'HTML-ENTITIES', $charset) );
$doc -> strictErrorChecking = false;
$doc -> formatOutput = true;
$xpath = new \DOMXPath( $doc );
$headings = $xpath -> query( '//h1 | //h2 | //h3 | //h4 | //h5 | //h6' );
$i = 0;
foreach ( $headings as $heading ) {
$slug = sanitize_title_with_dashes( $heading -> textContent, null, 'save' ); // The 'save' param tells WP to strip out all special characters so you don't get HTML entities in your IDs.
$slug .= '-' . $i;
$i++;
$heading -> setAttribute( 'id', $slug );
}
// Setting arguments on LoadHTML caused PHP to strip out some HTML tags. So
// instead of this: http://stackoverflow.com/a/22490902/343520
// I had to do this: http://stackoverflow.com/a/6953808/343520
// It keeps my encoding and all my tags intact, even if they're malformed.
// remove <!DOCTYPE
$doc -> removeChild( $doc -> doctype);
// remove <html><body></body></html>
$doc -> replaceChild( $doc->firstChild->firstChild, $doc->firstChild );
return $doc -> saveHTML();
}
add_filter( 'the_content', __NAMESPACE__ . '\\anchor_headings' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment