AliH

AI Engineer and Software Developer

Integrate highlight.js into WordPress for Code Highlighting Without Plugins

If you’re a WordPress user who frequently shares code snippets on your blog, you might be familiar with the struggle of finding the right plugin for code highlighting. While plugins offer convenience, sometimes you may prefer a lightweight solution without adding extra bloat to your site. In this tutorial, I’ll guide you through integrating highlight.js directly into your WordPress theme for elegant code highlighting.

Step 1: Enqueue highlight.js Assets

First, you need to enqueue highlight.js and its default stylesheet into your WordPress theme. Add the following code to your theme’s functions.php file:

function enqueue_highlight_assets() {
    wp_enqueue_style('highlight-default', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css');

    // Add custom CSS for styling code blocks
    wp_add_inline_style('highlight-default', 'pre.wp-block-code { font-size: 1rem; } .wp-block-code { padding: 0.5rem; border-radius: 0.5rem; }');

    wp_enqueue_script('highlight-js', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js', array(), null, true);
    wp_add_inline_script('highlight-js', 'document.addEventListener("DOMContentLoaded", function() { hljs.highlightAll(); });');
}
add_action('wp_enqueue_scripts', 'enqueue_highlight_assets');

This code registers and enqueues the necessary CSS and JavaScript files from the CDN provided by highlight.js. Additionally, it adds some custom CSS to style the code blocks to match your theme’s design.

Step 2: Display Code Snippets

With highlight.js set up, you can now display code snippets in your WordPress posts or pages using the pre and code HTML elements. Wrap your code snippet within these elements and assign the appropriate language class for syntax highlighting.

Step 3: Customize Highlighting

You can customize the appearance and behavior of code blocks further by tweaking the CSS and JavaScript settings. For instance, you can modify the colors, font sizes, or add line numbers to code blocks.

Conclusion

By integrating highlight.js directly into your WordPress theme, you can achieve elegant and lightweight code highlighting without relying on plugins. This method offers more control over the styling and ensures better performance for your website. Happy coding!


Comments

Leave a Reply

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