Acquiring the skill to showcase code effectively in WordPress is of utmost importance for bloggers and content creators who consistently publish code online for their audience to utilize. Computer code, as intended, generates a novel visual output on a website's front end, distinct from the tags, slashes, and brackets present within the actual code snippets.
However, this gives rise to a predicament for individuals writing about development and design, as they require a means to appropriately present the code without it executing its intended functionality, such as generating a button or applying styles to a paragraph block.
Put simply, when crafting a blog post that includes a code snippet as an example, it is imperative to prevent the code from executing. This approach allows readers to perceive the code in its original form, view it within a well-formatted block, and even copy its contents for their own development endeavors.
This guide aims to demonstrate various methods for displaying code in WordPress, irrespective of the chosen WordPress theme. Additionally, it will assist you in determining the most suitable method for your particular workflow.
Create Amazing Websites
With the best free page builder Elementor
Start NowWhat Happens When You Add Regular Code in WordPress?
When you add regular code directly into a WordPress post or page, without taking any specific measures, the code can cause unintended consequences. WordPress has built-in mechanisms that automatically process and sanitize content to ensure security and proper functionality. As a result, when regular code is added, it may be modified or stripped out completely by WordPress.
Here are a few things that can happen when you add regular code in WordPress:
- Code Alteration: WordPress might alter the code by removing or modifying certain elements to prevent potential security risks or conflicts with the platform's functionality. This can result in the code not executing as intended or producing errors.
- Code Stripping: WordPress has filters and security measures in place that may remove certain types of code deemed unsafe or unnecessary. This can lead to the removal of important code snippets or the entire code block itself.
- Visual Distortion: Code typically contains special characters, symbols, and formatting that may interfere with the visual presentation of your WordPress content. It can cause formatting issues, misalignment, or the code appearing as plain text rather than being rendered as code.
- Execution of Code: In some cases, if the code is not properly sanitized or handled, it may execute and perform its intended functionality. This can have unintended consequences, such as creating buttons, altering the appearance of the content, or even affecting the overall functioning of your website.
To overcome these issues and safely display code in WordPress, it is recommended to use appropriate methods or plugins specifically designed for showcasing code snippets. These methods ensure that the code is properly formatted, preserved, and displayed without any unwanted modifications or execution.
Here we are going to add the following HTML code in the snippet:
<!DOCTYPE html>
<html>
<head>
<style>
.cities {
background-color: green;
color: white;
border: 4px solid black;
margin: 10px;
padding: 10px;
}
</style>
</head>
<body>
<div class="cities">
<h2>Chicago</h2>
<p>A nickname for Chicago is The City of Broad Shoulders.</p>
</div>
<div class="cities">
<h2>Los Angeles</h2>
<p>A nickname for Los Angeles is The City of Angels.</p>
</div>
<div class="cities">
<h2>New York</h2>
<p>A nickname for New York is The Big Apple.</p>
</div>
</body>
</html>
This specific code excerpt employs HTML styling elements to generate three content blocks adorned in green, complete with headers and paragraphs.
Nevertheless, our intention is to present the unprocessed code within a blog post, rather than allowing it to render in the given blocks.
The following outcomes can be observed when the code is directly pasted into the WordPress Gutenberg Block Editor:
In view of the aforementioned, it is evident that WordPress endeavors to employ the code for its primary function of generating content. However, it removes the styling from the code, thereby failing to present the desired outcome to the readers.
To avert such circumstances, we strongly advocate the utilization of one of the methods enumerated below for the purpose of displaying code.
4 Ways To Display Code In WordPress
The following techniques are arranged in ascending order of difficulty, and we offer specific approaches tailored to individuals who derive satisfaction from composing code and content within markdown editors, as opposed to utilizing WordPress.
Method 1: Using the Gutenberg Block Editor
Gutenberg editor includes a pre-existing Code block that facilitates the presentation of code snippets while preserving their formatting and without executing the code.
To commence, access a post or page in WordPress and proceed to select one of the Add Block buttons.
Please select one of the "Add Block" buttons to proceed.
By doing so, the assortment of available blocks will be unveiled. You have the option to either search for the "Code" block or input a keyword such as "code" into the search bar.
Upon locating the Code block, identifiable by its bracket icons, proceed to click on it in order to insert a section of code into the post.
Presently, an area featuring the cue "Compose code…" ought to be observable to you.
The WordPress Gutenberg editor provides markdown support, enabling the discovery and insertion of Code blocks through the use of a forward slash (/) followed by the input of "C" or "Code" within the editor. WordPress will subsequently display all pertinent blocks, facilitating a more expedient insertion process.
It is important to note the distinction between the Code block and the Custom HTML block. While the Custom HTML block is intended for the inclusion of custom HTML code to be rendered on the frontend, the Code block is specifically designed for the addition of raw code for display purposes.
Presently, it is the appropriate moment to replicate the desired code and insert it into the designated area labeled as "Write Code..."
The code you have provided is now enclosed within the designated Code block.
An advantageous aspect of the Code block is its adherence to the formatting of spaces and tabs within the original code snippet. Consequently, the displayed code should maintain its visual consistency with the source from which it was copied.
To exhibit your code within your WordPress post or page, conclude the procedure by clicking on the "Publish" button. Furthermore, you have the option to obtain a visual representation of its appearance prior to publication by selecting "Preview."
After clicking the "Publish" button, proceed to access the live version of the post to verify that the code snippet is being displayed as raw code.
As observed, the Code block is characterized by its simplicity, yet it serves the essential purpose of preserving the formatting when presenting code within blog posts.
Refer to the provided screenshot below. In this particular example, the original code snippet remains unaltered; it is merely presented on the front end within a gray box.
In order to enhance the prominence of the Code block, it is advisable to consider modifying its default appearance.
To access the available styling choices for the block, kindly select the Code block and proceed to click on the Settings (gear icon) button. This action will open the Block tab, exclusively displaying the Block settings applicable to the selected block, namely, the Code block in this instance.
One has the ability to customize the Code block according to personal preferences, including the option to modify aspects such as text and background colors.
Method 2: Using a Plugin
Please utilize your preferred plugin installation method to incorporate the Enlighter – Customizable Syntax Highlighter plugin into your WordPress site.
Once activated, the plugin will be fully functional and allow you to insert code into any post/page through the Gutenberg block or Classic Editor Insert button.
If you are utilizing the WordPress Gutenberg Block Editor, access a post in which you desire to exhibit code. Select one of the Add Block buttons (identified by the "+" symbol) to unveil the assortment of available blocks.
Peruse or input a keyword pertaining to the Enlighten Sourcecode block. Proceed to click on the respective block in order to incorporate it within the post.
The Enlighter Highlighter block subsequently appears within the Block Editor interface, featuring a designated heading titled "Generic Highlighting" and a text input field labeled "Insert Sourcecode..."
Please input or copy and paste the desired code intended for display on WordPress into the designated "Insert Sourcecode..." text field.
In its capacity as a syntax highlighter, the plugin retains all formatting preferences and tabulations. Upon achieving satisfaction with the outcome, please proceed to select the "Publish" button.
By utilizing this functionality, you can access the user interface of your post in order to observe the same content as site visitors.
The Enlighter plugin provides a simplistic default theme for displaying code, accompanied by line numbers that aid in the structuring and referencing process.
As previously mentioned, utilizing a plugin to exhibit code on the WordPress platform offers distinct advantages when compared to alternative methods. An illustrative example of such an advantage is the frontend functionality provided by the Enlighter syntax plugin, wherein lines of code are dynamically highlighted as the user scrolls through the content.
Furthermore, within the code box located in the upper-right corner, there are several buttons that enhance the user experience. Notably, one of these buttons enables the presentation of the code in plain text format, devoid of line numbers.
The second button, denoted as "Copy To Clipboard," facilitates the instantaneous duplication of all contents within the code box, enabling users to conveniently transfer and paste the code into any desired program.
Lastly, the third button opens the code in a new window, thereby presenting it in a browser window formatted as plain text.
The Enlighter plugin offers a range of themes and robust customization tools to tailor the appearance of the code box according to your preferences. If you prefer not to utilize the default theme, you can navigate back to your post within WordPress and select the currently active Enlighter Sourcecode block.
This action will unveil the Block sidebar within WordPress. In case it does not immediately appear, kindly ensure you click on the Settings (gear icon) button located in the top-right corner of the WordPress window.
The initial customization option to consider is the Language field, as it instructs the plugin on which code language to display, enabling appropriate formatting and highlighting features.
There exists a considerable selection of coding languages to consider, therefore peruse the list and select the one that is most suitable.
The Speciallines feature emphasizes designated lines by allowing users to input line numbers separated by commas.
Consequently, the designated lines you have specified are visually emphasized for all individuals accessing the site.
The Lineoffset parameter provides a means to commence your coding snippet at a particular line number, proving advantageous when presenting a subset of code from a larger set of lines.
Evidently, by inputting the value "10" in the Lineoffset field, the entirety of the code box initiates from line number 10.
Method 3: Using an Encoder Tool
Please visit the W3Docs HTML Encoder website. On the page, you will find two adjacent box fields. The left one is designated for pasting your code, while the right one displays the encoded version that you can copy and paste into WordPress.
Before proceeding, it is necessary to specify the desired code preservation type:
- Select JavaScript Unicode if you plan to paste code containing JavaScript elements.
- Opt for HTML symbols if you are working with HTML.
Please insert the desired code to be displayed in WordPress into the designated field on the left. Subsequently, locate and select the Encode button located above on the right side.
The final outcome might appear perplexing; however, it is essentially an amalgamation of HTML elements aimed at preserving the entirety of the inserted code, while avoiding any unintended activation or display of alternative content on the frontend.
Please click the "Copy" button.
Return to WordPress and access the intended post or page. Proceed to select the Options (represented by three vertical dots) menu located in the upper-right corner. Subsequently, opt for the Code Editor feature.
The current interface will present the Code Editor instead of the visual Block Editor. Locate the desired section for code display and proceed to insert your encoded HTML into the editor.
In the event that you are utilizing the Classic WordPress editor, it is imperative to navigate to the Text tab, which corresponds to the Code Editor in the Gutenberg Block Editor.
Please select the "Update" or "Publish" option to finalize the post, and proceed to the front-end of the post to observe its visual presentation.
You will be able to observe the unaltered code that was initially inserted into the encoder, prior to the inclusion of HTML encoding elements. It is important to note that the encoders do not provide any styling capabilities, which makes this approach ideal for achieving a tidy and minimalist aesthetic.
Method 4: Using a Custom Shortcode
The creation of a custom shortcode fulfills the task of inserting reusable blocks of code without the need for manual copying and pasting. This is precisely why custom shortcodes provide a robust opportunity for code display on the WordPress platform.
The advantages of utilizing custom shortcodes for code presentation are as follows:
- Custom shortcodes enable the saving of intricate code sections for future reuse, eliminating the necessity to repeatedly type lengthy code snippets.
- It is possible to define personalized CSS styles for code highlighters and containers.
- Shortcodes can be employed by any user, enabling other contributors to effortlessly leverage your code highlighters and blocks with a simple click.
Creating a custom shortcode necessitates proficiency in modifying WordPress theme files, working with PHP code, and potentially developing WordPress plugins. As a result, crafting a custom shortcode for WordPress may pose difficulties for individuals new to PHP.
Nonetheless, the end result offers a considerably simpler approach to displaying code on the WordPress platform.
One has the freedom to choose any desired name for the custom shortcode and establish various alternatives, such as [html] [/html] and [css] [/css], to accommodate diverse programming languages.
Please be advised that for optimal syntax highlighting, it is advisable to utilize custom shortcodes in conjunction with the Text Editor (in WordPress Classic) or the Custom HTML box when working with the WordPress Gutenberg Block Editor.
The objective is to construct a bespoke shortcode that enables users to input or insert code within the delimited boundaries of the shortcode's opening and closing tags.
The objective is to develop a tailored shortcode that allows users to input or insert code within the designated opening and closing tags of the shortcode.
Wrapping Up
Displaying code in WordPress is crucial for sharing programming concepts, ensuring accuracy, improving aesthetics, and fostering collaboration. It allows developers to educate their audience, provide concrete evidence, enhance user experience, and encourage community engagement. Showcasing code snippets promotes transparency, trust, and reliable information. Custom shortcodes or plugins can ensure visually appealing and well-structured code display. Sharing code facilitates discussions, feedback, and innovation. Overall, effective code display in WordPress is essential for knowledge dissemination, quality assurance, and the growth of the WordPress development community.