Skip to content

Instantly share code, notes, and snippets.

@Wilto
Last active August 29, 2015 14:27
Show Gist options
  • Save Wilto/7b0f901a77c1b860c76e to your computer and use it in GitHub Desktop.
Save Wilto/7b0f901a77c1b860c76e to your computer and use it in GitHub Desktop.
you think this is a game
// https://www.youtube.com/watch?v=b9N3tIlEJNc
function normalize_headings( $content ) {
// Move all headings below H2 down one notch
$output = preg_replace( "/<(.*)h4(.*)>(.*)(<\/h2>)/", "<$1h5$2>$3</h5>", $content );
$output = preg_replace( "/<(.*)h3(.*)>(.*)(<\/h2>)/", "<$1h4$2>$3</h4>", $output );
// H1 and H2 both collapse to H3
$output = preg_replace( "/<(.*)h1(.*)>(.*)(<\/h1>)/", "<$1h3$2>$3</h3>", $output );
$output = preg_replace( "/<(.*)h2(.*)>(.*)(<\/h2>)/", "<$1h3$2>$3</h3>", $output );
print apply_filters( 'normalize_headings', $output );
}
add_filter('the_content', 'normalize_headings' );
@kadamwhite
Copy link

<?php
function switch_heading( $content, $fromHeading, $toHeading ) {
  // First capture group: from start of tag `<` through to the $fromHeading (e.g. "h2")
  // Second capture group: from after $fromHeading through to the end of tag `>`
  // Third capture group (.*? means "not greedy") is everything through to the closing tag
  $fromRegExp = '/<([^>]*)' . $fromHeading . '([^>]*)>(.*?<\/)' . $fromHeading . '>/';
  $toReplacement = '<$1' . $toHeading . '$2>$3' . $toHeading . '>';
  // https://www.youtube.com/watch?v=b9N3tIlEJNc
  // http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454
  return preg_replace( $fromRegExp, $toReplacement, $content );
}

function normalize_headings( $content ) {
  // Move all headings below H2 down one notch
  $output = switch_heading( $content, 'h5', 'h6' );
  $output = switch_heading( $output, 'h4', 'h5' );
  $output = switch_heading( $output, 'h3', 'h4' );
  // H1 and H2 both collapse to H3
  $output = switch_heading( $output, 'h2', 'h3' );
  $output = switch_heading( $output, 'h1', 'h3' );

  return $output;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment