Prettying up WordPress code blocks - Highlighting code with PrismJS

PrismJS로 코드 하이라이트 적용한 결과 화면 캡쳐
(The result of highlighting the code)

Hi! Have you ever posted code to your WordPress blog and realized that it looks too bland? I know I did at first, too.

But don't worry, today we're going to show you how to use the How to add the 'code highlight' feature to WordPressfor you.

In particular, the PrismJS(PrismJS), a powerful open-source tool, we'll take a deep dive into how to implement a beautiful Code Hightlight from start to finish without any plugins!

1. What is PrismJS?

PrismJaysis a lightweight code highlighting tool built on modern web standards. It's used on tons of websites and makes your code look more readable and professional. Prismajes offers a wide range of themes and plugins, so you can customize it to fit your blog's style.

2. upload your PrismJS file

To apply Prismajes, you must first download the necessary files and upload them to your current WordPress theme folder.

코드 하이라이트 적용 대상 언어 선택 화면
(Select a language to apply code highlighting to)

2-1. Download the file

  1. PrismJS Official Siteand click the Download button.
  2. The compression level is Minified version(minimized version).
  3. Themes are Okaidia(Featured).
  4. Select the language you need. By default, the Markup, CSS, C-like, JavaScriptand PHPfrom the list. I chose Python and R as additional choices.
  5. Select "Copy to Clipboard Button" from the plugin to add the ability to copy code.
  6. Click the Download JS and Download CSS buttonsto download the file.
 Copy to Clipboard Button 선택 화면
(Copy to Clipboard Button Selection Screen)

2-2. Upload your files to WordPress

Downloaded prism.jsand prism.css file inside the directory of the WordPress theme you're currently applying. assets/js and assets/css folder. The final path should look like this your-themerefers to the folder of the theme you are currently applying (e.g. Kadence, Twenty Twenty-Five, etc.).

  • /wp-content/themes/your-theme/assets/js/prism.js
  • /wp-content/themes/your-theme/assets/css/prism.css

3. functions.php and prism.js File settings

To apply PrismJS in WordPress functions.php file, and this is one of the most important parts of this post, so pay attention, review, and follow along.

3-1. functions.php Add code

  1. From the WordPress admin screen, navigate to Appearance > Theme File Editor.
  2. The child theme's functions.php file. The reason you want to use a child theme here is so that your customizations are preserved when the parent theme is updated. If you're not using a child theme, you'll want to set it up.
  3. Add the code below to the functions.php Add it to the bottom of your source code and update it.
function enqueue_prism_scripts() {
    // Prism CSS
    wp_enqueue_style(
        'prism-css',
        get_stylesheet_directory_uri() . '/assets/css/prism.css',
        array(),
        '1.29.0'
    );

    // Prism JS
    wp_enqueue_script(
        'prism-js',
        get_stylesheet_directory_uri() . '/assets/js/prism.js',
        array(),
        '1.29.0',
        true
    );
}
add_action('wp_enqueue_scripts', 'enqueue_prism_scripts');

This code will load the PrismJS and CSS files on all pages. You can also add conditional statements to load them on specific pages only.

3-2. prism.js Add code

To use the plugins you selected when you downloaded Prism.js (e.g. Toolbar, Copy to Clipboard), add the following These files are located in the /wp-content/themes/your-theme/assets/js/prism.js Here it is. It's easy to apply using the theme editor, as shown above.

// Activate the Toolbar plugin
document.addEventListener('DOMContentLoaded', function () {
    Prism.plugins.toolbar.registerButton('copy-to-clipboard', function (env) {
        var button = document.createElement('button');
        button.innerHTML = 'Copy';
        button.addEventListener('click', function () {
            navigator.clipboard.writeText(env.code);
        });
        return button;
    });
});

By adding this code, you can copy that source code at once via the 'COPY' button in the codeblock.

4. Using in the Gutenberg Editor

To apply PrismJS in the Gutenberg editor, follow these steps. In case you're wondering what this editor is, it's your usual post editor.

  1. Add or select a block of code. This is done by typing '/code', as you know.
  2. With your mouse cursor hovering over the code block, click Settings - Block in the Block panel, and then click Advanced section of the page.
  3. Additional CSS class(es) field in the language-[language name]in the JavaScript code. For example, you can use the JavaScript code → language-javascript for example.

5. Warnings and tips

  • Always use the child theme. Your settings will be preserved even if the parent theme is updated.
  • Optimize your file size by selecting only the languages you need. The smaller the file, the faster the page loads.
  • Adding the ability to copy code makes it more convenient for visitors to use your code.
  • Choose a PrismJS theme that matches your theme colors. This will improve readability.

6. Troubleshooting and FAQs

Q: Code highlighting isn't working for me.
A: Make sure you've entered the code correctly in your functions.php file, and that your prism.js and prism.css files are in the right places.

Q: Highlights for certain languages are not working.
A: Make sure you selected the appropriate language when you downloaded PrismJS. If you need to, try downloading it again.

Q: My pages have become slower to load.
A: Remove unnecessary languages and plugins, minimize the file, and try again.

Finalize

Now you too can display your code beautifully like a pro! If you still have any questions, please leave them in the comments. Let's figure it out together! 😊.

If you think this is too difficult or dizzying, you can just apply the code copy button to the Easily create a copy code button in WordPress: WPCode! Check out the post to find out!

# Glossary

  • wp_enqueue_scripts: How to load scripts and styles correctly in WordPress
  • Code highlightsThe ability to highlight programming code with color and style to make it look good
  • PrismJS: JavaScript-based code syntax highlighting library
  • Gutenberg: WordPress' basic block editor
  • Child themesChild theme that can be modified while retaining the functionality of the parent theme
  • Syntax highlightingColor-coded syntax for programming languages
  • functions.phpPHP files that can extend the functionality of your WordPress theme.
테리 이모티콘
(Happy coding!)

Similar Posts