Block Code Highlighting In WordPress

Block Code Highlighting In WordPress

(Last Updated On: February 10, 2017)

Since this blog is going to be mostly about web development and programming, one of the things we need to do is add syntax highlight. Syntax highlight helps making the code on your site more readable by highlighting and coloring the blocks of code.

After reviewing a few I have decided to go with prism. It is available as a plugin in wordpress, feel free to install it via search in plugins section or download it here.

Full description of prism.js can be found here, but for the sake of this post we will use some basic examples. It will require you to switch to “Text” mode of the editor when adding the code blocks. To highlight the code just put an opening <pre> and <code> tags before the code and </pre> and </code> right after. Refer to full description if you need full list of features or supported languages, but we will show you the basic usage next.

If you need the line numbers to show in the code block, change opening <pre> to <pre class=”line-numbers”>.

To specify the language, add “language-name” class to opening <code> block, such as <code class=”language-php”> or <code class=”language-css”>.

As a basic example, lets try to add a css code block. When writing a post, switch to “Text” mode and add the following lines:

<pre><code class=”language-css”>

p {

color: #000000;

margin: 0;

}

</pre></code>

The result should look just like:

p {
  color: #000000;
  margin: 0;
}

Now lets try to highlight a php block and show the line numbers:

<pre class=”line-numbers”><code class=”language-php”>

<?php

echo ‘Hello World’;

?>

</code></pre>

Which will show as:

<?php
  echo 'Hello World';
?>

 

This is it for the basic usage.

 
I also recommend installing WP-Markdown to auto-convert html elements. Basically, <?php needed to be entered as &gt;?php without it to be displayed correctly in html.

Rasim Adjiasmanov on FacebookRasim Adjiasmanov on LinkedinRasim Adjiasmanov on Twitter
Rasim Adjiasmanov
Web Developer
Rasim is a veteran web developer who started building websites in 90s while still in middle school. The passion for the web grew stronger since childhood. After graduating University of Southern Indiana with Computer Information Systems degree in 2006, Rasim worked on a number of projects and helped building a number of companies.

Leave a Reply

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