What I want to do
Sharing code in posts on WordPress is quite a pain with all the HTML escaping to take care of. So, I plan to enclose code in posts within a custom shortcode called [sourcecode]
, as shown below, and let it automatically escape the special characters.
[sourcecode]
<?php
// Some code here.
?>
[/sourcecode]
The code
And this is what the relevant function (in my theme’s functions.php) looks like:
/**
* 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();
// New shortcodes below
add_shortcode( 'sourcecode', 'bbcode_code' );
$content = do_shortcode( $content );
$shortcode_tags = $orig_shortcode_tags;
return $content;
}
/**
* 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( '&', ' ', '<', '>', ''', '"', '/', '[', ']' ),
// ...with the HTML entities below, respectively
array( '&', '\0', '<', '>', ''', '"', '/', '[', ']' ),
$content
);
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
*
* http://core.trac.wordpress.org/browser/trunk/src/wp-includes/shortcodes.php
*/
Question(s)
Now that the explanation is out of the way…
-
Am I missing anything else?
For example, until I read the source of SyntaxHighlighter Evolved plugin, I didn’t know that