Skip to content

Instantly share code, notes, and snippets.

@Dan-Q
Created February 26, 2024 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dan-Q/8268cf224e3c26c9da8d19d9e59d5752 to your computer and use it in GitHub Desktop.
Save Dan-Q/8268cf224e3c26c9da8d19d9e59d5752 to your computer and use it in GitHub Desktop.
Include from your theme file. Use [footnote]This is the content of my footnote.[/footnote] to add a footnote.
<?php
/**
* Footnotes
*/
function footnote($atts, $content = '') {
global $footnote_number, $footnote_contents;
$footnote_number ??= 0;
$footnote_contents ??= [];
$footnote_number++;
$post_id = $GLOBALS['post']->ID;
$footnote_name = "footnote-$post_id-$footnote_number";
$footnote_ref = "footnote-ref-$post_id-$footnote_number";
$inline_content = esc_attr(wp_strip_all_tags($content));
$footnote_contents[] = [
'id' => $footnote_number,
'name' => $footnote_name,
'ref' => $footnote_ref,
'content' => $content,
];
return "<sup><a name=\"$footnote_ref\" href=\"#$footnote_name\" title=\"$inline_content\" class=\"footnote-ref\">$footnote_number</a></sup>";
}
function footnotes_reset_count($content){
global $footnote_number;
$footnote_number = 0;
$footnote_contents = [];
return $content;
}
function footnotes_display_after_content($content){
global $footnote_contents;
if( ! $footnote_contents ) return $content;
if( empty( $footnote_contents ) ) return $content;
$content .= "<div class=\"footnotes\" style=\"font-size: 80%; margin-top: 0.5em; padding-top: 0.5em; border-top: 1px solid #666;\"><h2 class=\"sr-only\">Footnotes</h2>";
foreach($footnote_contents as $footnote) {
$content .= "<p class=\"footnote\" data-footnote-name=\"${footnote['name']}\"><sup><a name=\"${footnote['name']}\" href=\"#${footnote['ref']}\">${footnote['id']}</a></sup> ${footnote['content']}</p>";
}
$content .= "</div>";
$footnote_number = 0;
$footnote_contents = [];
return $content;
}
add_shortcode('footnote', 'footnote');
add_filter('the_content', 'footnotes_reset_count', 10);
add_filter('the_content', 'footnotes_display_after_content', 11);
function allow_shortcodes_in_captions($out, $pairs, $atts) {
$out['caption'] = do_shortcode($out['caption']);
return $out;
}
add_filter('shortcode_atts_caption', 'allow_shortcodes_in_captions', 10, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment