Get my FREE ebook:
"SEO FOR BLOGS: The Ultimate Guide"
Limited Time Offer!

How To Display Code Properly Within Your WordPress Blog Posts

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:

1
2
3
4
5
6
7
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
(It's Free)
Sté Kerwer
Post written by: Sté Kerwer
Bonjour from France. My name is Stéphane Kerwer and Dukeo.com is my blog. I do most of the heavy lifting in here but from time to time, you may see some guest posts. If you wish to receive updates about Dukeo, subscribe to RSS Feed, follow Dukeo on twitter or become a fan on Facebook.
7 Comments
  1. Gorman
    Gorman

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

  2. Shad
    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
    Jony

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

  4. Michelle
    Michelle

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

  5. Sarah
    Sarah

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

  6. Anon
    Anon

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

    • Dana
      Dana

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

arrow