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( '&', '\0', '<', '>', '\'', '"', '/', '[', ']' ),
// ...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
\0
also needs to be replaced with\0
"to work around kses" (which wasn't clear enough for me).And other than escaping the special characters, is there anything else that I could possibly be missing? Am I doing it the right way?
(It would be great if anyone could take a look at this file (PHP source code of SyntaxHighlighter Evolved plugin) and see if you can find something that I need to implement. I already did try my best though.)
PS: Why not use the plugin itself? For one, I don't want the syntax highlighting that it does; and I want to know if what it does can be implemented easily.
'code longtext not null'
. . . I was playing with the snippets idea and did a CPT with only title and a textarea custom field and didn't found much problem in displaying them withhtmlentities
. . . Anyway, nothing in depth, just sharing a bit of research.