Pro Tips

How to Add Syntax Highlighting for Code Snippets in WordPress

Using Prism.js to add syntax highlighting for code snippets in your WordPress theme is a great choice. Here’s a step-by-step guide to implement Prism.js:

1. Download Prism.js

First, go to the Prism.js website and download the version that suits your needs. You can customize it by selecting the languages you need and any additional plugins or themes.

2. Upload Prism.js Files to Your Theme

Upload the downloaded prism.js and prism.css files to your WordPress theme directory. You can use an FTP client or the file manager provided by your hosting service.

3. Enqueue Prism.js and Prism.css in Your Theme

Add the following code to your theme’s functions.php file. This will enqueue Prism.js and its CSS so that it’s loaded with your theme:

function add_prism() {
    // Enqueue PrismJS
    wp_enqueue_script('prism-js', get_template_directory_uri() . '/path-to-prism.js', array(), null, true);

    // Enqueue PrismJS Stylesheet
    wp_enqueue_style('prism-css', get_template_directory_uri() . '/path-to-prism.css');
add_action('wp_enqueue_scripts', 'add_prism');

Make sure to replace /path-to-prism.js and /path-to-prism.css with the actual paths to where you uploaded these files in your theme directory.

4. Use Prism.js with the <pre> Tag

In your posts or pages, wrap your code snippets with <pre> and <code> tags and specify the language. For example:

<pre><code class="language-css">
/* Your CSS code here */

5. Customize (Optional)

You can add custom styles to your prism.css file or in your theme’s CSS file to further customize the appearance of your code blocks.

6. Test Your Setup

Create a post or page with a code snippet formatted as shown above. Publish it and view the post or page to ensure that Prism.js is working correctly.

7. Update and Maintenance

Regularly check for updates to Prism.js for any new features or security updates. You can replace the prism.js and prism.css files with the updated versions as needed.

By following these steps, you should be able to seamlessly integrate Prism.js into your WordPress theme and beautifully display color-coded code snippets.

Leave a Reply

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