How to Highlight Code on the Front end of WordPress

Sometimes, you find yourself needing to highlight code on the front end of a website. Traditionally, this is done with one of the many coding plugins out there. However, I wanted to see if this could be done without using any additional plugins, and it wound up being a lot easier than you’d think.

Adding highlight.js

First, to show highlighted code on the front end, I needed to include the highlight.js library. This is a reliable and independent library for highlighting and is the same library that is used in Jetpack’s Markdown Block.

To do this, I added the following code to the site using a code snippet plugin such as WPCodeBox. This script uses cdnjs to deliver the files. However, you can always download the files locally and call them that way, or create your own plugin to add the scripts.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/highlight.min.js"></script>

Next, I created another snippet that checked the content on each page and highlighted code on the front end if necessary. I set this script to run everywhere in the Header:

document.addEventListener("DOMContentLoaded", (event) => {
    hljs.configure({
        cssSelector:'pre.lx-code code',
    });

    hljs.highlightAll();
});

This configuration looks for any HTML elements that start with <pre class="lx-code"> and then contains a nested <code> element. I created this specification so that I could still use other code blocks from time to time.

Displaying Highlighted Code

So, the code we previously added looks specifically for a class. In this case, it is the class lx-code. As long as Gutenberg block, Oxygen element, Breakdance element, etc, has that class, our code will decipher it and then display the highlighted code on the front end.

Furthermore, we can add additional language classes to let highlight.js know exactly what language the code is in and reduce some guesswork. Some examples would be lanugage-php, language-js, langauge-css, or language-html. This isn’t always necessary, but it can’t hurt when you remember. I’m not sure if this helps to increase performance.

For example, in this post, the code shown is using Gutenberg’s native Code element and the class has been assigned via Block > Advanced.

Adding classes to highlight code on the front end

Naturally, I tried to get a little fancier with this and created an Oxygen Gutenberg Block. This worked to an extent, but I realized there was a problem when pasting in some code, specifically <link> or <script> tags. For some reason, Gutenberg seems to apply these script or link HTML tags when pasting into a page instead of just pasting them as text…no matter how you try to paste it in. I tried setting Oxygen’s elements to use the <pre> and <code> tags assigned them the wp-block-code class, but nothing seems to work.

So, the solution to just use a straight Code block from Gutenberg works for posts. This, could be a better long-term solution as if you decide to deactivate the highlight.js script, your website doesn’t break and the default Gutenberg settings for displaying code takes over.

It definitely could be possible to convert this into a plugin that creates a custom Gutenberg block. However, in the case of Gutenberg, it would make more sense just to use one of the existing Highlighting solutions out there.

Using Code Highlighting in Oxygen

As mentioned above, my idea to turn this into an Oxygen Gutenberg block failed due to some back-end Gutenberg settings. However, I still had plans for using this in Oxygen with how I was going to set up the CodeBitts for this site. I wanted certain content on those pages to be highlighted automatically, and make it as easy as possible. You can see an example of this here:

Code Highlighting working on the front end of an Oxygen template
Code Highlighting working on a CPT in Oxygen

This is similar to how the WP.org Developer’s documentation highlights functions. I accomplished this using Dynamic Data with a custom field. I used Pods in this scenario, but you can use whatever plugin you’d like.

To accomplish this, I created two fields. The first was called codebitt_expanded_title and was a plain text field. The second field was called codebitt_language, and contained a simple list of available languages.

Next, I opened the Oxygen template for the CodeBitt post type and wrote the following code to get this expanded title and display it:

<?php
global $post;

$cb_expanded = pods_field_display('codebitt_expanded_title');

if($cb_expanded) {


	if(has_post_parent()) {
		$cb_expanded = get_the_title($post->post_parent).' '.$cb_expanded;
	}

	$cb_lang = pods_field('codebitt_language');


	if($cb_lang) {
		$language_tag = "language-".$cb_lang;

		echo '<h1 class="lx-code text-2xl '.$language_tag.'">'.$cb_expanded.'</h1>';
	}

}

?>

This code grabs the expanded title, figures out the desired language, and then displays it once the page is rendered.

Additionally, if I wanted to display code in an Oxygen element, I simply need to use a text element that uses the <pre> or <code> tag, and assign the class lx-code to it.

    Leave a Reply

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

    © 2020-2024 Luxibay
    Name(Required)
    Please let us know what's on your mind. Have a question for us? Ask away.
    This field is for validation purposes and should be left unchanged.