How to highlight code in WordPress

WordPress Editing Tabs

Although it’s easy to use WP Chili out of the box, WordPress does have some limitations, like the following:

  • you need to change to the Code editor before adding a snippet to your post
  • you need to make your snippet postable yourself, escaping all HTML entities
  • even if snippets are very short, they are intermingled with their explanations and it’s tricky to concentrate on writing the best post with so many distractions in between

Using WP Chili & Enzymes

Now I’ll show you a better approach by using together WP Chili 1.0 and Enzymes 2.2.
All you need to be up and running is the classical roundtrip: download, unzip, upload, and activate.

How to highlight code snippets

You can start by writing a simple enzyme for automating things, like the following hilite custom field: {[ .hilite | .hilite( =php= ) ]}

hilite can be used with the following patterns:

  1. {[ =snippet= | .hilite( =language= ) ]}
  2. {[ .snippet | .hilite( =language= ) ]}

The first pattern comes in handy when you want to highlight some very short and naive snippet
{[ =echo htmlentities( $name );= | .hilite( =php= ) ]} renders {[ =echo htmlentities( $name );= | .hilite( =php= ) ]}

So far, so good, but if the snippet has a character that WP texturizes, then hilite seems to fail. In fact
{[ =$welcome = “Hello “.$name;= | .hilite( =php= ) ]} renders {[ =$welcome = “Hello “.$name;= | .hilite( =php= ) ]}

The above issue is not a hilite‘s bug but it could be fixed by adding new code to it, or with new enzymes along the pathway, like the following requote custom field: {[ .requote | .hilite( =php= ) ]}

which makes that
{[ =$welcome = “Hello “.$name;= | .requote() | .hilite( =php= ) ]}
renders {[ =$welcome = “Hello “.$name;= | .requote() | .hilite( =php= ) ]}

The best option is to add another custom field for hosting your snippet and use the second pattern: in fact hilite‘s snippet has been rendered by {[ .hilite | .hilite( =php= ) ]} and requote‘s one by {[ .requote | .hilite( =php= ) ]}.

How to highlight code files

Sometimes you have a file that you want to show in its entirety, and having to copy it into a custom field is annoying or maybe not an option, if the file is alive, for example.

In such cases you can use an enzyme like the following file custom field: {[ .file | .hilite( =php= ) ]}

It’s use is again very simple and very similar to the above patterns:
{[ .file( =blog/wp-content/plugins/hello.php= ) | .hilite( =php= ) ]} renders {[ .file( =blog/wp-content/plugins/hello.php= ) | .hilite( =php= ) ]}

One Reply to “How to highlight code in WordPress”

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.