How to Correctly Display Code in a WordPress Post

How to Correctly Display Code in a WordPress Post

Do you want to display code in WordPress post? If yes then this article is for you. Displaying code as regular text will not be displayed correctly. This is because WordPress will run your post through several cleanup filters prior to saving your post. The purpose of the filters is to make sure no code is injected through the post editor to hack your website. This post discusses the different methods you can use to display code.

Display using the default editor

This is the option for beginners and users who don’t display code in WordPress post often. It is easy. You just go to the post edit screen and ‘add a new code block’ to the post. From the new block you will be able to enter your code in the text area. Once you are done just click on save and preview your code block. You are done.

Display code using a plugin

There are several WordPress plugins you can use to display code. This option is ideal for people who display code in WordPress post often. The best thing about using the WordPress plugin is that you will be able to display code in just any programming language, display code with the syntax highlighting and line numbers and also allow users to study the code as well as copy it.

SyntaxHighlighter Evolved is a popular WordPress plugin for displaying code. Install and activate it. Go to the area you want to display the code in your post and then add the ‘SyntaxHighlighter Code’ block. Enter the code in the text area and change the block settings the way you want.

The first step is to choose the language of your code. You can then turn off the line numbers, provide first line number, highlight the line you want and turn off features to make links clickable. Save the post and click preview to view the code. SyntaxHighlighter Evolved has several themes and color schemes you can use to customize your code. You can make changes in the plugin’s settings.

Display code manually

This is the option for the advanced users because it involves a lot of work. It is ideal if you are using the classic editor. To get started your code has to be passed through an online HTML entitles encoder tool. This will change the markup of your code to HTML entities. That way the code will be able to pass the WordPress cleanup filters. Once that is done copy-paste the code in your text editor and wrap it around <pre> and the <code> tags. You can then save the code and preview.

Display code in WordPress post