PrismJS (syntax highlighter) with WordPress

I use Prism JS to prettify the code blocks on this WordPress blog. Here I will show a quick, 5-minute, very simple way to add it on your own blog. No plugin required!

1. Download PrismJS:

Download prism.js and prism.css:
https://prismjs.com/

Detailed download instructions at the end of this article.

2. Move files to your theme folder:

Move prism.js and prism.css to wp-content/themes/{your-theme-name}


If you don’t know your theme name, go to Admin, click Appearance > Theme Editor:

Your theme name is in the select at right:

3. Edit your theme functions.php:

On the theme editor, click on “Theme Functions” and add this code:


function add_prism()
{
    wp_enqueue_style( 'prism-css',  get_stylesheet_directory_uri() . '/prism.css' );
    wp_enqueue_script( 'prism-js',  get_stylesheet_directory_uri() . '/prism.js', [], false, true );
}
add_action( 'wp_enqueue_scripts', 'add_prism' );

That’s it!


How to use:

WordPress 5 (Gutemberg):

Just add a paragraph block and set it as a code:

Then, click on advanced and add the class language-php for PHP, language-bash for bash, etc.

Alternatively, use the HTML block with a <pre class="language-php"><code>...</code></pre>.

If your code contains < symbols, you need to escape them OR to use the “Unescaped markup” Prism plugin. if you use this plugin, you can replace <pre><code> tags with <script> tags.

WordPress 4 (Classic)

Edit the HTML (Text tab) and wrap your code in <pre class="language-php"><code>...</code></pre> tags.

If your code contains < symbols, you need to escape them OR to use the “Unescaped markup” Prism plugin. if you use this plugin, you can replace <pre><code> tags with <script> tags.


EXTRA: Downloading Prism.js/css

On the official page, click on Download

Select (1) Minified, (2) your preferred theme (I use Okaidia), (3) the languages you are going to use (if in doubt, select all):

Then, down on the same page, select (4) plugins (if in doubt, select all), (5) Download JS, (6) Download CSS:

Save files as prism.js and prism.css

Close Menu