On my personal blog, I would like commentors to be able to post code using certain shortcodes (eg [html], [css], [js], [php]). I still want to strip tags for comments for security reasons, but allow them between those shortcodes. When I write a test comment, "[html]<p>sample code</p>[/html]" becomes "[html]&lt;p&gt;sample code&lt;/p&gt;[/html]". To get around this, I came up with the following code but I cannot get it to work. Could someone tell me what I am doing wrong? Thanks!

function process_code_tags($comment)
  $comment = preg_replace_callback('/(\[html\])(.*?)(\[\/html\])/imsu',  create_function('$matches', 'return $matches[0].htmlspecialchars_decode($matches[1]).$matches[2];'), $comment);      
  return $comment;
//add_filter('preprocess_comment', 'process_code_tags');
add_filter('comment_text', 'process_code_tags', 9);
  • Any other ideas besides Christopher's? Sep 27, 2011 at 4:12

1 Answer 1


You want to allow folks to post code in their comments, like on here were we can just do <p>something</p> without having to worry about doing any &gt; or &lt; stuff? I think you'll still want those special html characters converted to their respective entities, but you need to stay under the radar to avoid getting the tags stripped out by wp_filter_kses.

You'll need to hook into a filter called pre_comment_content and convert anything within your shortcode tags to their HTML entity equivalents.

add_filter('pre_comment_text', 'wpse29367_pre_comment_text', 9 );
function wpse29367_pre_comment_text( $text )
    $text = preg_replace_callback( 
        create_function( '$matches', 'return $matches[1] . htmlspecialchars( $matches[2] ) . $matches[3];' ),
    return $text;

Then you can decode them or whatever in the shortcode function you create:

add_action( 'init', 'wpse29367_add_shortcode' );
function wpse29367_add_shortcode()
    add_shortcode( 'html', 'wpse29367_shortcode_cb' );

function wpse29367_shortcode_cb( $atts, $content = NULL )
     * decode html entities here if you want
     * eg: 
     * return htmlspecialchars_decode( $content );

The final piece of the puzzle, adding the do_shortcode filter to comment_text.

add_filter( 'comment_text', 'do_shortcode' );

You could make this work very well for your visitors by using a plugin like SyntaxHighlighter Evolved, and just using the first bit of code I posted along with adding the do_shortcode filter to comment_text.

Note: didn't test any of the above. Copy and paste with caution.

  • Thanks Chris. I am using Syntax Highlighter Evolved. That part is working fine, it's just displaying the entities. Sep 25, 2011 at 2:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.