Add Prism.js Syntax Highlighting to WordPress without Plugin

Want to add Syntax Highlighting for your Code Block in WordPress without adding any extra plugins? Here is how to do it in under 2 minutes. Follow the steps below.

Add the below code to your child theme’s functions.php. This code calls the Prism’s JS and CSS file from the theme folder and puts it to work.

/* Prism JS Syntax Highlighting WordPress */
function wpflt_prism_highlighter() {
    if ( is_single() ) {
        wp_register_style ( 'prism-css', get_stylesheet_directory_uri() . '/prism.css' );
        wp_register_script( 'prism-js', get_stylesheet_directory_uri() . '/prism.js' );
        wp_enqueue_style('prism-css');
        wp_enqueue_script('prism-js');
    }
}
add_action('wp_enqueue_scripts', 'wpflt_prism_highlighter');

Now, go to the Prism website and download the JS and CSS customized according to your liking. Here is the customized setting we use on our site.

Once the files are downloaded, place the files in your child theme folder. It should appear in the ‘Theme File Editor’ page in WordPress.

Done!. For any code you add, remember to add the corresponding classes. You can inspect the class of above code.

We used two classes, language-php for PHP and line-numbers for Line Numbering. For more details on classes, visit the prisms website.

Benefit of not using plugins is that, they add a lot of extra JS files which we don’t really use. This saves that extra KB contributing to the page size.