Configure and download PrismJS
No plugin required! Download prism.js
and prism.css
from https://prismjs.com/download.html. Select Compression level, Theme of your choice, then Languages. You can also select Plugins if you want.
Once you’re satisfied with the configurations, click on the Download JS and Download CSS buttons to download your PrismJS syntax highlighter javascript and css files as prism.js and prism.css.
Copy PrismJS files to WP Theme folder
Upload prism.js and prism.css to wp-content/themes/[theme-name]
Edit your theme functions.php
You should use child theme already. If you are not, then I hope you know what you are doing. Add the following code to your theme’s function.php file:
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' );
Bonus: line break for the code block
As mentioned on PrismJS github issues and on StackOverflow, PrismJS doesn’t enable line break by default. So you might find your codes in long lines with horizontal scroll bars. To enable line wrapping in your code blocks you need to set white-space: pre-wrap
in the CSS.
How to Use?
In the Gutenberg Block editor, select Add block, in the search for a block bar type /code and you will find the Code Block. Paste your code. In the Block Setting Advanced field, type appropriate language class. For example, language-css for CSS, language-python for Python.
For the HTML block, use <pre class="language-XXX"><code> you code...</code> </pre>
.