How to Display Code Snippets in a WordPress Page

Apr 11, 2024

Display Code Snippets in a WordPress Divi Page

Learn how to enhance your code snippets on WordPress Divi page using the SyntaxHighlighter Evolved plugin and Prism.js libraries. Link these libraries to your theme and utilize their classes for syntax highlighting in various programming languages.

Step1

Install SyntaxHighlighter Evolved Plugin

  • Go to Plugins > Add New and search for “SyntaxHighlighter Evolved.”
  • Click on Install Now and then Activate the plugin.

Step 2

Create or Edit a Post/Page in Divi

  • Go to Posts > Add New or Pages > Add New to create a new post or edit an existing one.
  • create a new section and insert a  text module .

 

Step 3

Show Code Blocks on a WordPress Divi Page

Insert Code Snippet in the text tab of  the text module

Wrap your code snippet with

<pre> and <code>  

like this :

Very important :

To prevent the code from being executed and display it as plain text, you need to encode the code by replacing < and > with their respective HTML entities (&lt; and &gt;). For example, if you have a tag like <script>, it should be encoded as &lt;script&gt;.

There are several websites that can help you encode your code with HTML entities.

your code should be like this :

Here is an example what what you should see :

 

step4

Enqueue SyntaxHighlighter Evolved Scripts and Styles

To display the code with syntax highlighting and style, you need to add SyntaxHighlighter Evolved’s script libraries to your WordPress theme. Follow these steps to do so:

Step 1: Edit the functions.php File

  1. Open the File Editor

    • Navigate to Appearance > Theme Editor in your WordPress admin area.
  2. Add the Following Code to functions.php

    • Paste the following code at the end of your functions.php file and save the changes:


function enqueue_prism() {
    // Enqueue Prism.js CSS
    wp_enqueue_style('prism-css', 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.25.0/themes/prism.min.css');

    // Enqueue Prism.js JavaScript
    wp_enqueue_script('prism-js', 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.25.0/prism.min.js', array(), null, true);

    // Enqueue Prism PHP plugin
    wp_enqueue_script('prism-php', 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.25.0/plugins/autoloader/prism-autoloader.min.js', array('prism-js'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_prism');

 

Step 5

Now that you have linked the libraries to your theme, you can use its classes. Go back to your code and inside the “<code>” tag, insert the relevant class for your code language. Here is a list of available classes:

For PHP:  language-php
For JavaScript:  language-javascript
For HTML:  language-html
For CSS:  language-css

For example, to highlight JavaScript code, you would wrap your code like this: