Skip to content
Ruhani RabinRuhani Rabin

How to Add Source Code Highlights and a Copy Button in WordPress

WPCodeBox
Enhancing the readability and functionality of your source code snippets can be a game-changer for your WordPress site. Today, let's talk about how to add source code highlights and a handy "Copy Code" button to your site—without using any plugins!

Highlight.js Initialization

First, we'll use Highlight.js to make your code snippets look great. Highlight.js is a fantastic library that automatically styles your code snippets, making them more readable and aesthetically pleasing.

Step 1: Enqueue Highlight.js Scripts and Styles

To start, we'll need to load the Highlight.js library and its CSS styles from a CDN. This ensures that your code snippets are styled correctly.

Step 2: Adding Copy Code Button

Next, we enhance the Highlight.js functionality by adding a "Copy Code" button to each code block. This button lets users easily copy code snippets to their clipboard with just one click!

Making it Work

Using a bit of PHP, we can enqueue the necessary scripts and styles, then add a JavaScript snippet that initializes Highlight.js and appends the "Copy Code" button to each code block.

Step 3: Wrap Standalone Code Tags

To ensure all your standalone <code> tags within <p> tags are correctly highlighted, a PHP filter will wrap these within <pre> tags. This is a crucial step for consistent styling.

Step 4: Custom Styles

Finally, we add custom CSS styles. This will style the pre and code elements and the "Copy Code" button, ensuring everything looks clean and professional. And that's it! You've now enhanced your WordPress site with beautifully highlighted code that's easy to copy. This improves the aesthetic and enhances user experience by making code snippets more functional and user-friendly.

Additional Snippets

Instructions for WPCodeBox:

  1. Add a new snippet in WPCodeBox.
  2. Paste the script
  3. Save it once, then Enable it, and Save it again
  4. Clear your cache
  5. Check your existing PRE or CODE tags
You can also apply this using a functions.php file or a custom plugin.
View on GitHub
Share: