If you need to display code snippets in your WordPress blog you have several options. I’m going to talk about Google Prettify today. The reason being is that it’s free, open source, and you don’t need a plugin. You could choose from a variety of plugins if desired, but I want to focus on doing it yourself without a plugin today.
What is Google Prettify?
The first thing you need to do is to add a script to your WordPress Blog. I use the plugin Insert Headers and Footers by WpBeginner. It’s lightweight, intuitive, and works very well without any need to modify WordPress files.
Using the header inserter plugin, add this code into the header,
<pre class="prettyprint"> code goes here </pre>
Note that it’s much easier to use an html widget such as what is included with Elementor page builder to add programming code – instead of messing with the WordPress text editor. See this post for more information.
With this basic configuration, most of the code will be displayed on your blog post. However, some coding such as php and script tags won’t display at all. The reason is that WordPress automatically strips this out. To fix the problem you will need to escape the code. This can be done manually (ugh) or you can do it the easy way. I prefer simple so I used FreeFormater to auto escape the code. Just copy and paste the original script into the escape tool, then copy the escaped version back to your blog within the pre tags.
Escaped Code Example
Here is the before and after script when using an escape tool.
You can customize how you want the code to be highlighted by applying skins. Here is the theme gallery. To use a custom theme, add skin=yourtheme; You can also specify the language such as css.
As an example, to use the desert skin configure the script like this.
It is not required to specify the language like I did, because Prettify will attempt to guess which one you are using.