WordPress: Format and colorize code block by applying prism.js

Motivations

for (int i = 5; i < 10 ; i++) { Console.WriteLine("Hello Moto?"); }

If you are using Vantage for your WordPress site, and you want to make your code block looks fancy, follow the instructions:

Instructions

1. Make sure you have created a child theme based on Vantage, and it's activated.

2. Reset styles applied to code block.

I highly recommend to work with WP-SCSS plugin when writing CSS/SCSS, so you can have stylesheets organized without the costs of performance by using @import.

/* Reset the style set by Vantage (the parent theme) */ .entry-content pre, .entry-content code { background: unset; font-family: unset; border: unset; box-shadow: unset; overflow-x : unset; }

Later we will apply prism.js and its stylesheet.

3. Insert code snippits to your child theme's "functions.php"

function code_pre_theme(){ // To check if currently viewing page is a "post" if (is_singular('post')) { wp_enqueue_script('prism-js', 'https://cdn.jsdelivr.net/ npm/prismjs@1.28.0/prism.min.js'); wp_enqueue_script('prism-core-js', 'https://cdn.jsdelivr.net/npm/prismjs@1.28.0/components/prism -core.min.js'); wp_enqueue_style('prism-css', 'https://cdn.jsdelivr.net/npm/prismjs@1.28.0/themes/prism.min.css'); wp_enqueue_script( 'prism-autoloader-js', 'https://cdn.jsdelivr.net/npm/prismjs@1.28.0/plugins/autoloader/prism-autoloader.min.js'); } } add_action('wp_enqueue_scripts&#039 ;, 'code_pre_theme', 10); //Number 10 heres depend on site. The princlple is to set a number larger than the essential scripts and styles belong to your parent theme, which is vantage in this case.

By enqueuing prism-core.min.js and prism-autoloader.min.js, it will utomatically loads languages's style when necessary.
You may opt-in languages based on your needs. For example, to load certain style based on has_tag('php'), has_tag('csharp') result.
Visit prism.js at cdnjs.com for more programming language supports.

Conlusion

You don't have to follow every steps as I did, as you may come up with a better solution for your own site.

At the time I wrote this article, I absolutely have zero knowledge in PHP, only knowing C#, Javascript, Java, SCSS; writing and modifying some php script isn't complicated, so go ahead and try all the possibilities.

Posted in Wordpress 網站開發, 網站開發 and tagged , , , .

Leave a Reply

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