Skip to content

Writing Source Code In Blog Posts

Writing my last article, I had some trouble inputting code into the WordPress editor, I Googled around and it’s a little tricky to figure out if you’re not a coding guru (for me at least), so I’ve got some resources and my own take on it below.

ESCING CODE

Chris Coyier has a thorough post on posting code blocks on WordPress over at CSS-Tricks (WordPress also has a post on the topic). The way I went with, that Chris covers (he also covers using Markdown and Prism.js that you should definitely check out), is escaping the code. That basically means changing all the ‘<‘ and ‘>‘ in the code to ‘&lt;‘ and ‘&gt;‘, respectively.

For CSS, it’s not a big deal, but for HTML, JavaScript, or PHP it becomes a problem. After you’ve escaped all the special characters, you now wrap the code around a <pre> tag, followed by a <code> tag.

  • The <pre> tag (preformatted text) basically takes how everything is written in your code, spaces and breaks, as-is, which is very useful when showing code hierarchy.
  • The <code> tag is meant to define your phrase as computer code, which you can use CSS to further customize the text.

As an example of how I did the code in the previous post, I had it exactly as:

<pre>
<code>
&lt;?php get_header(); ?&gt;

/* index.php code, probably looping functions to display recent posts */

&lt;?php get_footer(); ?&gt;
</code>
</pre>

Which outputted as:

<?php get_header(); ?>

/* index.php code, probably looping functions to display recent posts */

<?php get_footer(); ?>

Remembering that this is all done in the Text editor, not the Visual editor of WordPress:
screenshot

Published inBlog

Comments are closed.