wordpress & prismJS code syntax highlighting in Twenty Twenty One theme (No plugin)
In this website I’m using wordpress twenty twenty one theme with some extra child theme modifications. Trying to improve the code block and adding some syntax highlighting, I was looking on many different plugins but I decided to use prismJS without plugin.
What is prismJS ?
Prism is a lightweight, extensible syntax highlighter, built with modern web standards in mind. It’s used in millions of websites, including some of those you visit daily
- Dead simple Include prism.css and prism.js, use proper HTML5 code tags (
- Intuitive Language classes are inherited so you can only define the language once for multiple code snippets.
- Light as a feather The core is 2KB minified & gzipped. Languages add 0.3-0.5KB each, themes are around 1KB.
- Blazing fast Supports parallelism with Web Workers, if available.
- Extensible Define new languages or extend existing ones. Add new features thanks to Prism’s plugin architecture.
- Easy styling All styling is done through CSS, with sensible class names like
Lets start applying prismJS
1. Download prism.js and prism.css
From the download page choose prism options, languages, themes, plugins
Click on minified version, select theme (in my example is okaidia), and start selecting the languages you will use in your posts and from plugins I selected “Copy to Clipboard Button”.
Once you are ready click download JS and download css from the bottom of the page.
In your download folder you will have 2 files, prism.css & prism.js
In my case with twenty twenty one theme I had some issues with the default css font-family in prism.css, code fonts did not appearing properly, removing the font-family from the prism.css worked as expected.
I opened the file with my editor and removed the font-family part completely.
font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;
2. Upload prism files in your Child theme
upload prims.js & prism.css in child theme root folder
file path: /wp-content/themes/twentytwentyone-child/
3. Update functions.php file
Add the following code part in functions.php (wp-content/themes/twentytwentyone-child/functions.php)
my updated functions.php file:
4. Use prismJS in wordpress code block
In a new post/page add a code block, paste your code, tag the document with “code”, and in block properties click advanced and add additional CSS class in format “language-[SupportedLanguage]”
In my previous example was php and class name was “language-php”.
Supported Languages list: https://prismjs.com/#supported-languages