Posting Code in WordPress (and comments!)

As you may have noticed, I often post code (including (X)HTML) in these posts. A classic problem is how to display a line like <html_tag> without having the web browser treat it as a tag and trying to process it. [UPDATE: Fix for comments!]

There’s an excellent plugin called Code Markup that handes this very nicely. Basically, it allows adding an attribute to the <code> tag so that it reads (among other options)<code allow="none". Once this is done, all > and < characters are escaped, and no HTML will be processed.

The original plugin, however, does not work in comments. Thus, visitors cannot discuss code snippets! By making a two line change, however, this can be fixed.

Open up the file /path/to/wordpress/wp-content/plugins/code-markup.php and look at line 41. There, the plugin registers two filters to be run on the_content, which means a post. By changing the lines which read:

// Priority 1 - encode XML before we do anything else
add_filter('the_content', 'tguy_cmu_encode_xml', '1');
// Priority 11 - fix escaped slashes after wpautop() has added them
add_filter('the_content', 'tguy_cmu_fix_quotes', '11');

To have the following after them:

// Do the same for comments
add_filter('comment_text', 'tguy_cmu_encode_xml', '1');
add_filter('comment_text', 'tguy_cmu_fix_quotes', '11');

We can now have it apply this fix to comments as well! Go ahead, try it!

8 responses to “Posting Code in WordPress (and comments!)”

  1. Ok. On line 109, there’s a check if ($allow == 'none' || $allow == ''). If you add the following below that, we can remove rel=”nofollow” from within the <code> tag. Normal links will still have rel=”nofollow”.

    $escapedContent = preg_replace("/(]*( |\t|\n)rel=)('|\")(([^\3]*( [^ \3]*)*) )?nofollow/", "$1$3$5", $escapedContent);
    $escapedContent = preg_replace("/(]*)( |\t|\n)rel=(''|\"\")([^>]*>)/", "$1$4", $escapedContent);

    The only problem with this is that if the user himself puts in rel=”nofollow”, it won’t be kept. I’m not sure (yet) how to fix that.

    These regular expressions were taken from the DoFollow plugin.

  2. Thanks. There’s one remaining issue that needs to be fixed — I don’t think wordpress should be allowed to insert rel=”nofollow” into the href’s wrapped by code. However, I can’t just remove all rel=”nofollow” lines, because the user may have put them there.

    I’ll look into it, but I’m not sure exactly how to do this.

Leave a Reply

Your email address will not be published. Required fields are marked *