Skip to content

Instantly share code, notes, and snippets.

@kingkool68
Last active August 29, 2015 14:21
Show Gist options
  • Save kingkool68/2d2b85dbd93169c78959 to your computer and use it in GitHub Desktop.
Save kingkool68/2d2b85dbd93169c78959 to your computer and use it in GitHub Desktop.
Simple WordPress Footnotes
<?php
function api_footnotes( $content ) {
$post_id = get_the_ID();
//Need to correct wpautop() which smart-quoteify's the " in the numoffset argument.
$content = preg_replace('/numoffset=&#8221;(\d+)&#8243;/i', 'numoffset="$1"', $content);
//Microsoft has some weird space characters that Mac/Unix systems don't have. What the next line does is replace the weird space characters with a real space character which makes the regex work...
$content = str_replace('[ref ', '[ref ', $content);
$start = 1;
$notes = array();
if (preg_match_all('/\[(ref((\s+)?numoffset="(\d+)+")? (.*?))\]/s', $content, $matches) ) {
/*
Given [0. numoffset="5" This is a footnote]
$matches[0] = The whole match including the square brackets: [0. numoffset="5" This is a footnote]
$matches[4] = numoffset value: 5
$matches[5] = The footnote text: This is a footnote
*/
foreach( $matches[0] as $index => $target ) {
$offset_value = (int) $matches[4][$index];
$text = trim( $matches[5][$index] );
//Footnotes that have [ or ] in the text break. Use double curly quotes as an escape to workaround this.
$text = str_replace('{{', '[', $text);
$text = str_replace('}}', ']', $text);
if( $offset_value > 0 ) {
$start = $offset_value;
}
$notes[] = $text;
}
$n = $start;
foreach( $matches[0] as $index => $target ) {
$content = str_replace($target, "<sup class=\"footnote\"><a href=\"#footnote-$post_id-$n\" id=\"fnref-$post_id-$n\">$n</a></sup>", $content);
$n++;
}
// *****************************************************************************************************
// Workaround for wpautop() bug. Otherwise it sometimes inserts an opening <p> but not the closing </p>.
// There are a bunch of open wpautop tickets. See 4298 and 7988 in particular.
$content .= "\n\n";
// *****************************************************************************************************
$content .= "<div class='footnotes'>";
$content .= '<ol start="' . $start . '">';
$i = $start;
foreach($notes as $note) {
$content .= "<li id=\"footnote-$post_id-$i\">$note <span class=\"footnotereverse\"><a href=\"#fnref-$post_id-$i\">&#8617;</a></span></li>";
$i++;
}
$content .= "</ol>";
$content .= "</div>";
wp_enqueue_script( 'api-footnotes' );
}
return $content ;
}
add_filter('the_content', 'api_footnotes', 98); //Set priority to 98 so links are converted to footnotes before Yoast's analytics injects outbound tracking events.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment