How to Display Highlighted Source Code in WordPress

Including code snippets in technical articles can be very helpful for demonstrations and examples. For instance, if you want to show readers how to write a WordPress plugin, you may want to include some PHP code snippets in your post.

There are a few different options for adding source code snippets to your WordPress posts. Here, we’ll outline three of them.

Adding Source Code Using the Editor

One option for adding code snippets to your WordPress posts is to use the built-in block editor, which comes with newer versions of WordPress. The block editor includes a “Code” block type, which allows you to easily include source code in your post.

While this method is relatively simple to use, it does not provide syntax highlighting for the code, which may not be suitable for more technical posts that require this feature (more options that allow syntax highlighting below in this post).

To add a code block using the block editor, simply type “/code” in the block editor and a new code block will be created. You can then paste your code into this block.

Display Source Code With a Plugin

Syntax highlighting has become a standard feature in source code presentation, as it helps make code easier to read and understand. Users often expect to see syntax highlighting, especially when such advanced options are available in widely used tools like GitHub. Therefore, including syntax highlighting in your code snippets can be a useful feature for your readers.

If that’s the case, and you’re looking for syntax highlighting for your source code snippets, you may want to consider using a plugin like SyntaxHighlighter Evolved. This plugin allows you to easily add syntax-highlighted code snippets to your WordPress posts.

To use the plugin, simply install it and then wrap your source code snippet in brackets that include the programming language of the code. For example, to add a Python code snippet, you can write:

text = 'visualime'

All of the code within these tags will be automatically and dynamically highlighted based on the syntax of the chosen programming language.

Display Source Code Without a Plugin or Block Editor

If you are using an older version of WordPress that does not have the block editor, or if you prefer not to use a plugin, you can also use the classic editor to add a code snippet to your post.

To do this, switch to the “Text” tab (instead of the default “Visual” tab) in the classic editor. Then, you can wrap your source code in the following format, which will tell the browser to display the code as a code section:

<pre><code>CODE HERE</code></pre>

This method allows you to include code snippets in your WordPress posts without the need for additional plugins or the block editor. However, it does not provide syntax highlighting or other formatting options.






Leave a Reply

Your email address will not be published. Required fields are marked *