This post will show you how to write code in your WordPress posts, and have that code display as code for your readers. This is not to be confused with executing code in your posts, that’s different and will be covered in a future post. So, why would you need to display code in your posts? Well, for me, it was because many of the posts here are to show you how to hack your WordPress posts and pages and it’s much easier to show you examples of the code changes rather than just talk about it.
I am working on a project called Show in a Box and we needed to have two loops on the front page of a theme we are building. I will be posting a tutorial of how to accomplish this, and I needed to be able to insert the PHP code to show people what changes they need to make. *If you would like to know how to create multiple loops, please sign up for regular updates by subscribing to this blog via email or RSS.
The problem is that WordPress either tries to actually execute the code, or rewrites it. That makes it unusable without some help. That help comes from a plugin called SyntaxHighlighter and can be found here.
You can see the result of this plugin below:
<?php if (have_posts()) : ?><br /> <?php while (have_posts()) : the_post(); ?>
Pretty snazzy eh? If you look closely you’ll see some handy options across the top of that window above, “view plain”, “copy to clipboard”, and “print”. That’s very convenient for users who are trying to make changes to their code.
The best part about this plugin is that it not only works with PHP code, but many others. Here’s a list from the developer’s website:
- C++ —
- C# —
- CSS —
- Delphi —
- Java —
- PHP —
- Python —
- Ruby —
- SQL —
- VB —
- XML/HTML —
In future posts you’ll learn how to execute PHP code in your posts and pages, and other WordPress tips, tricks, and hacks.