Skip to content

Instantly share code, notes, and snippets.

@aahan
Last active March 28, 2024 19:27
Show Gist options
  • Save aahan/6746179 to your computer and use it in GitHub Desktop.
Save aahan/6746179 to your computer and use it in GitHub Desktop.
Enclose code blocks within [code] shortcode, and let PHP and WordPress take care of the rest.
<?php
/*
* Functionality to set up custom shortcode correctly.
*
* This function is attached to the 'the_content' filter hook.
*/
add_filter( 'the_content', 'run_bbcodes', 7 );
function run_bbcodes( $content ) {
global $shortcode_tags;
$orig_shortcode_tags = $shortcode_tags;
$shortcode_tags = array();
// Add custom shortcodes below
add_shortcode( 'code', 'bbcode_code' );
$content = do_shortcode( $content );
$shortcode_tags = $orig_shortcode_tags;
return $content;
}
/*
* Allow code shortcode in comments
*
* This function is attached to the 'comments_template' filter hook.
*/
add_filter( 'comments_template', 'bbcode_in_comments' );
function bbcode_in_comments() {
// Add custom shortcodes below
add_shortcode( 'code', 'bbcode_code' );
add_filter( 'comment_text', 'do_shortcode' );
}
/*
* Add Custom shortcode functions below
*
* This function is attached to the 'sourcecode' shortcode hook.
*/
function bbcode_code( $atts, $content = null ) {
// Ensure contents of a <pre>...</pre> HTML block aren't converted into paragraphs or line-breaks
$content = clean_pre( $content );
$content = str_replace(
// Replace these special characters...
array( '&', '<', '>', '\'', '"', '/', '[', ']', '\0' ),
// ...with the HTML entities below, respectively
array( '&amp;', '&lt;', '&gt;', '&apos;', '&quot;', '&#47;', '&#91;', '&#93;', '&#92;&#48;' ),
$content
);
return '<pre><code>' . trim( $content ) . '</code></pre>';
}
/*
// ALTERNATIVE 'bbcode_code' function
function bbcode_code( $attr, $content = null ) {
// Ensures that contents of a <pre>...</pre> HTML block aren't converted into paragraphs or line-breaks
$content = clean_pre( $content );
$content = str_replace(
// Replace these special characters...
array( '/', '[', ']', '\0' ),
// ...with the HTML entities below, respectively
array( '&#47;', '&#91;', '&#93;', '&#92;&#48;' ),
// PHP function automatically replaces characters that have special significance in HTML (i.e. & < > ' ")
htmlspecialchars( $content, ENT_QUOTES )
);
return '<pre><code>' . trim( $content ) . '</code></pre>';
}
*/
/*
* Related sourcecode worth reading:
*
* https://bitbucket.org/cbavota/syntax-highlighter-plugin/src
*
* https://github.com/mdawaffe/Highlight.js-for-WordPress/blob/master/highlight-js.php
*
* https://github.com/fracek/highlight-wp/blob/master/highlight.php
*
* http://plugins.svn.wordpress.org/syntaxhighlighter/trunk/
*
* http://blog.webspace.jp/235
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment