Prism Js代码高亮教程

Published
2022-12-08
浏览次数 :  232

Are you wondering how to add syntax highlighting to your WordPress site and blog posts built with either the Gutenberg editor or the Classic editor?

Perhaps the regular code snippet styling in the Gutenberg or Classic editor is too boring and you want to share snippets that look like they came from an actual code editor (IDE)?

Well, you’re in luck, Prism.js syntax highlighting for WordPress has you covered.

Prism is a syntax highlighter that will prettify all of the code snippets you put on your WordPress blog posts or pages.

Not sure what I mean by a syntax highlighter or wondering what does a syntax highlighter do? Here’s an example.

Your code snippets will go from looking something like this:

const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  );

// Examples
getURLParameters('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); // {}

To this!

const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  );

// Examples
getURLParameters('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); // {}

Copy

Pretty neat, huh?

In this article, I will teach you how to implement Prism.js syntax highlighting into your WordPress site without a plugin.

You could install a plugin to give you syntax highlighting in your WordPress site, but I try to avoid adding plugins whenever possible so my site loads faster.

Best of all, Prism is very lightweight, so it won’t slow your site down. The core code is only 2KB in size when it is minified and gzipped which is tiny.

Prism is a lightweight, extensible syntax highlighter, built with modern web standards in mind.

Also, if you need anymore convincing that Prism is the best syntax highlighter for WordPress to use, I should note that many well-known sites use it including CSS Tricks, Stripe, Mozilla, and even React’s main site.

Follow the 5 steps below to learn how to add Prism.js syntax highlighting to your WordPress site:

TABLE OF CONTENTS

Start Blogging 101 is reader-supported. If you purchase through a link on my site, I may earn a commission. Learn more

1. Choose Prism Options

First, go to the Prism download page. You’ll see a page like the one below:

Prism JS Syntax Highlighting WordPress Download Page

Here, you will see a whole bunch of options that you can choose to customize how your code will look with Prism.

For the first section that says “Compression level”, choose “Minified version.” This will shorten the amount of text used in the background code, therefore allowing it to run quicker on your site.

Next, you will choose the Theme that you want to use. I chose the Okaidia theme, but feel free to choose whatever theme you think will look best with your site.

As you click on the various themes, you’ll notice that the code blocks above the “Download JS” and “Download CSS” buttons will change to give you an idea of how the code will look with your chosen theme.

Next, choose the languages that will be used within the code blocks on your site.

For me, I left the defaults checked which are MarkupCSSC-like, and JavaScript. I also chose PHP because WordPress snippets of code are almost always written in PHP. That covers the vast majority of languages that I plan to show within my blog posts.

However, if you know for sure that you’ll be using Python, TypeScript, or SQL for example, just check any of those boxes. Keep in mind, though, that the more languages you have checked, the bigger your JavaScript and CSS files will be.

So, just make sure that you choose only the languages you need. You can always go back and add the background code for another language if you find out that you needed one that you didn’t get at first.

As far as plugins go, you can read about those yourself by checking out the “Plugins” section here.

The plugins give a little extra functionality if desired such as having line numbers show up in your code blocks or adding a “copy” button to the code so others can easily copy it. I personally chose the “Copy to Clipboard Button” plugin which you can see by hovering over any of the prettified code snippets on this page.

How to Add Prism JS Syntax Highlighter to WordPress Plugins and Download Buttons

If you’re on desktop, check out the copy button when you hover over this code snippet:

let button = document.getElementById('clickMe');

button.addEventListener('click', function(e) {
  e.preventDefault();
  document.execCommand('copy', false, document.getElementById('select-this').select());
});

Copy

Now that you have all your Prism JS syntax highlighter options chosen, it’s time to move to Step 2!

2. Download Prism JS and CSS Files

For the second part, you will be downloading your Prism JS (JavaScript) and CSS (Cascading Style Sheets) files.

Once you have your compression level, languages, and plugins selected that you want, you are ready to download the files you’ll be putting on your site.

Click on the big “Download JS” and “Download CSS” buttons as shown at the end of Step 1 and save each of these files somewhere on your machine.

This will create a prism.js and prism.css file in your Downloads folder.

Now it’s time to take these synxtax highlighter JS and CSS files and upload them to your WordPress child theme which I will cover in Step 3.

3. Upload Prism Files to Child Theme

After your prism.js and prism.css files are downloaded, you are ready to upload these files to the back end of your site.

You will not be using WordPress for this part. You will be logging onto the back end of your hosting provider (whether that be SiteGround or whatever hosting company you use). For most hosting providers, you will be accessing cPanel.

If your hosting provider uses something other than cPanel, then simply go to the area where you can access your domain files.

After you are logged in to your hosting back end (in this case, cPanel), click on “File Manager”. SiteGround’s File Manager is shown here:

Upload Prism JS CSS Files SiteGround File Manager

Once you click on “File Manager,” it may ask you which directory you want to go to. Choose “Document Root for {your website}” and click “Go”:

Add Syntax Highlighting to WordPress Tutorial Document Root cPanel

Now, path out to your theme’s folder. If you use a child theme (which you should be), path out to that theme’s directory. Or, if you’re just using a parent theme, go there.

You can find your theme’s folder by going to wp-content/themes/your-theme-name.

For Start Blogging 101, I am using the Kadence theme along with a Kadence child theme. If you haven’t heard of the Kadence theme, you should read how the Kadence theme won my award for the best WordPress theme for 2020.

Since I am using the Kadence theme with a Kadence child theme, my child theme’s folder is located at wp-content/themes/kadence-child.

Once you are in the appropriate theme folder (such as a child theme folder), you should see some files in there already such as style.css and a functions.php. This is the folder where you will be uploading the prism.css and prism.js files that you downloaded.

Now it’s time to upload your files.

Add Syntax Highlighting to WordPress cPanel Upload

Hit the “Upload” button as shown in the screenshot above. An upload page should open up. Browse out to the prism.css file that you have stored on your computer and choose that file.

If the upload page has a section for “Permissions,” just leave the default of 6-4-4 as seen below:

Prism JS cPanel Upload Permissions

Now, do the exact same steps for your prism.js file.

Once that is complete, if you go back to where your directory was showing, you should see both the prism.css and prism.js files sitting in your child theme’s folder now as seen below:

Prism JS Syntax Highlighter cPanel Child Theme Files

Good job! Time to move on to Step 4.

4. Add PHP Function to Load Prism

Your Prism files are now uploaded to the back end of your site. Great! All we have left to do is to make sure they get loaded up in our site whenever a page of our site comes up in a browser. This will require some more work on the back end where we were just working.

Remember the folder we were just in? wp-content/themes/your-theme-name? We will be working in that folder again. However, this is why it’s very important that YOU ARE USING A CHILD THEME because we will be working with the child theme’s functions.php file.

You should NEVER modify the parent theme’s functions.php file because it can mess up how your site works, and, after your theme updates, you will probably lose any work you did in your parent theme’s functions.php file.

Okay, now that I’ve made that clear, find the functions.php file in your child theme’s folder. In my case, it’s found in wp-content/themes/kadence-child .

Right-click this file and choose “Edit”. After you do that, a box may appear saying that you should back up your file in case anything goes wrong. Feel free to back up the contents of the file somewhere if you feel like you’ll be messing things up.

However, chances are you haven’t even added anything to your child theme’s functions.php file yet which means there would be nothing to back up. Anyway, click “Edit” on that popup box.

A rather ugly text editor page should show up in your browser. If you have been in this file already, there may be text you’ve already written (or maybe the theme’s creator added some comments in there). Otherwise, it will be blank.

If the file is blank, it will look something like this:

<?php
/**
 * Add custom functions here
 */

Copy

Here, you will be writing the code to have your Prism files load up whenever someone opens a page on your site.

I won’t get into huge detail here, but the proper way to include custom scripts and styles on your site (if you’re using WordPress) is to first register the file, and then enqueue it. You can read some great documentation on including CSS and JavaScript into your WordPress site here.

**Note: I am going to be showing you two different ways that you can include your Prism files on your site. The first way, it will load your Prism JS and CSS files on every single page on your website. This shouldn’t really slow anything down because the files are very small. However, the second way shows you how to conditionally load your Prism JS and CSS files so that they only load on certain pages and will be more performant.

In order to do this, we will write a simple PHP function right in our functions.php file. The first option loads your Prism files on every page of your website. The second option conditionally loads your Prism files only on certain pages so that they aren’t running when they don’t need to. I’ll explain both options below.

Option 1: Load Prism files on every page of your website

<?php

// Function to add prism.css and prism.js to the site
function add_prism() {
    
    // Register prism.css file
    wp_register_style(
        'prismCSS', // handle name for the style 
        get_stylesheet_directory_uri() . '/prism.css' // location of the prism.css file
    );

    // Register prism.js file
    wp_register_script(
        'prismJS', // handle name for the script 
        get_stylesheet_directory_uri() . '/prism.js' // location of the prism.js file
    );

    // Enqueue the registered style and script files
    wp_enqueue_style('prismCSS');
    wp_enqueue_script('prismJS');
}
add_action('wp_enqueue_scripts', 'add_prism');

Copy

Option 2: Conditionally load Prism files only on blog posts that have a tag of “code”

<?php
/**
 * Add custom functions here
 */

// Function to add prism.css and prism.js to the site
function add_prism() {

    if ( is_single() && has_tag( 'code' ) ) {
        
        // Register prism.css file
        wp_register_style(
            'prismCSS', // handle name for the style 
            get_stylesheet_directory_uri() . '/prism.css' // location of the prism.css file
        );

        // Register prism.js file
        wp_register_script(
            'prismJS', // handle name for the script 
            get_stylesheet_directory_uri() . '/prism.js' // location of the prism.js file
        );

        // Enqueue the registered style and script files
        wp_enqueue_style('prismCSS');
        wp_enqueue_script('prismJS');

    }
}
add_action('wp_enqueue_scripts', 'add_prism');

Copy

**Note: If you know some PHP code, you do NOT need to include the closing ?> PHP tag as this may cause errors on your page, so copy the files above exactly as you see them.

For Start Blogging 101, I personally used Option 2. The reason I used option 2 is because I only want to load my Prism files when absolutely necessary. It’s not necessarily a bad thing to have them load on every page since they are so small, but why load them on every page if you don’t have to?

In Option 2, notice the extra line that is added from Option 1. The added line is shown below:

if ( is_single() && has_tag( 'code' ) ) { 
    // function here 
}

Copy

Using is_single() means that I want the Prism files to load only on blog posts, so that means that my Home page and regular pages such as About and Contact don’t load the files – nice!

The second part && has_tag( 'code' ) means that I only want the files to load if it’s a blog post and there is a tag of “code” on my blog post. That way, I can very easily specifically target blog posts that have code snippets in them. It also means that the Prism files don’t load on blog posts that don’t need them such as ones with no code snippets.

If I write a blog post and want Prism to make my code snippets look pretty, now all I have to do is add a tag of “code” and follow the instructions in Step 5, and voila! The Prism files load only on that page, my code snippets are prettified, and everything looks beautiful.

Conditionally Load Prism JS Syntax Highlighter WordPress Posts With Tag Code

5. Use Prism in WordPress Gutenberg and Classic Editor

After you save your changes on your functions.php file, you should be ready to rock n’ roll! The last part is actually using the syntax highlighter within one of your WordPress blog posts. I’ll show you how to use Prism JS in the WordPress Gutenberg editor and also the Classic editor if you’re still using that.

WordPress Gutenberg Editor:

If you are using the new WordPress Gutenberg editor, then follow the method below. Speaking of which, you should be using the new WordPress Gutenberg editor because the Classic editor will only be supported until the end of the year 2021.

In order to have your code snippets prettified by Prism JS using Gutenberg, simply add a code block by clicking on the + button and adding a code block otherwise you can type /code in your editor and a code block will show up.

How to Add Prism JS WordPress Gutenberg Editor Code Block

Choose the code block and then type or paste the code that you want to show. It will initially look something like this:

<a href="https://startblogging101.com" target="_blank">Start Blogging 101</a>

Once you have your code written in your block, all you have to do now is give the code block the appropriate CSS class to get the Prism syntax highlighting to kick in.

With the code block in focus, go to your Settings button in the upper-right and find the Advanced tab at the very bottom of the right panel.

Expand the Advanced tab and you’ll see a text area for Addtional CSS Class(es). In here, type language- followed by whatever language your code is in.

For example, if it’s HTML code, you would type language-markup, if it’s JavaScript, you would type language-javascript, if it’s PHP, you would type language-php, and so on.

If you are unsure what you should put after the language- piece, check out the supported languages section on the PrismJS site.

Prism Syntax Highlighting WordPress Gutenberg Code Block Advanced CSS

After you give your code block the appropriate CSS class, you’re good to go!

Keep in mind, the code block will still look like the same boring code styling in your Gutenberg editor, but as soon as you Preview your blog post, you will see the code block transformed into Prism goodness! Your code block will now look like this:

<a href="https://startblogging101.com" target="_blank">Start Blogging 101</a>

Copy

Also, if you happen to use the inline code option within your Gutenberg paragraphs, all you have to do is add the appropriate CSS class to your paragraph block.

Make sure the paragraph block is in focus, go to Settings, expand the Advanced section and add the appropriate language- CSS class to your paragraph and it will <strong>look like this</strong> for all your inline code.

That’s all there is to it! You have now successfully implemented Prism JS syntax highlighting into your WordPress blog posts using the Gutenberg editor.

WordPress Classic Editor:

If you are still using the Classic WordPress editor, use this method for Prism JS in your blog posts.

While you are writing a blog post in the Classic editor using WordPress, simply use the “Text” tab. There are two tabs that you can choose from while writing a post – a “Visual” tab and a “Text” tab. The “Text” tab allows the writer to include their own HTML.

When you want to write a code block using the new Prism syntax highlighting that you just implemented, you will start your code block with the normal <pre><code> tags like you normally would. Except now, all you need to do is assign a class to your <code> tag.

If the code block is going to be written in HTML, you would start it with <pre><code class="language-markup">. If it will be in JavaScript, it would be <pre><code class="language-javascript"> and so on.

Got it? Here’s an example. In order to get an example code block written in JavaScript to take on the syntax highlighting from Prism, this is the full code you would have to write in the text tab of your blog post.

<pre><code class="language-javascript">
var myObject = {
    property1: "something",
    property2: 5,
    property3: true
}; 
</code></pre>

Copy


That’s it! You now have the power of using Prism syntax highlighting on all of your code blocks written in either the WordPress Gutenberg editor or the Classic editor. This is perfect for developers or anyone who includes code snippets as a part of their posts.


Top