Dukeo » WordPress » Display Code: How to Do this Right with WordPress

Display Code: How to Do this Right with WordPress

Steven 7 responses WordPress

You may have noticed it, but I share code on an extremely regular basis in my WordPress blog posts. While there are many plugin-based solutions to display code on your blog, it’s always best to find plugin-free solutions to your WordPress questions.

An interesting way of displaying code properly within your WordPress blog posts is to change the behavior of WordPress with some pre-determined HTML tags. In this example, I’ll be using the <pre> and </pre> tags.

Simply paste the following code in the functions.php file of your WordPress theme:

function pre_entities($matches) {
  return str_replace($matches[1],htmlentities($matches[1]),$matches[0]);
$content = preg_replace_callback('/<pre.*?>(.*?)<\/pre>/imsu',pre_entities, $content);

This piece of code will automatically replace content in <pre> and </pre> tags by HTML entities.

If you enjoyed this article,
Get email updates

Join for Free »


  1. Gorman

    A very useful tip. I’ll be using this in the future! Thanks again.

  2. Shad

    You definitely do post them often, and I don’t know what I would do if you didn’t! I keep a little file of them so that I can reference them, since I’m code illiterate lol! Thanks a million!

  3. Jony

    This could be exactly what I need for my next post. Thanks so much for posting these, they are great!

  4. Michelle

    Good to know! This may come in handy soon, thanks!

  5. Sarah

    I think we’re all really glad that you know how to do this and that you share with us. :) Thanks!

  6. Anon

    So now everyone can spread the word and share their code knowledge. Very cool!

    1. Dana

      Or their lack thereof, in my case. ;) One day I will learn how to do these things!