This tutorial explains how to add a "one-click copy" button to syntax-highlighted code blocks in WordPress posts. If you have already implemented code highlighting using a previous tutorial, you can proceed directly. If not, it is recommended to first set up code highlighting.
This guide focuses solely on adding the copy functionality.
Step 1: Load the Clipboard.js Library
The functionality relies on the Clipboard.js library. You can load it via CDN or from your local server.
Method 1: Using a CDN (Recommended for Testing)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/clipboard.min.js"></script>
Method 2: Local Loading
1. Download the library from the Clipboard.js website.
2. Upload the clipboard.min.js file to your theme's directory, e.g., /wp-content/themes/your-theme/js/.
3. Add the following line before the closing </head> tag in your theme's header.php file:
<script src="<?php echo get_template_directory_uri(); ?>/js/clipboard.min.js"></script>
Step 2: Implement the Copy Button Functionality
Add the following JavaScript to your theme's main JS file (e.g., main.js or custom.js). This code dynamically adds a copy button to each code block and handles the copy event.
Note: This code assumes your highlighted code blocks are wrapped in <pre><code>...</code></pre> tags and are inside a container with the class .single-content. Adjust the selector (.single-content pre) to match your theme's HTML structure.
document.addEventListener('DOMContentLoaded', function() {
var codeBlocks = document.querySelectorAll('.single-content pre');
codeBlocks.forEach(function(preBlock, index) {
var codeElement = preBlock.querySelector('code');
if (!codeElement) return;
var copyId = 'copy-code-' + index;
codeElement.id = copyId;
var copyButton = document.createElement('button');
copyButton.className = 'copy-code-btn';
copyButton.setAttribute('data-clipboard-target', '#' + copyId);
copyButton.textContent = 'Copy Code';
copyButton.setAttribute('title', 'Click to copy');
preBlock.style.position = 'relative';
copyButton.style.position = 'absolute';
copyButton.style.top = '8px';
copyButton.style.right = '8px';
copyButton.style.padding = '4px 8px';
copyButton.style.fontSize = '12px';
copyButton.style.cursor = 'pointer';
copyButton.style.backgroundColor = '#007cba';
copyButton.style.color = '#fff';
copyButton.style.border = 'none';
copyButton.style.borderRadius = '3px';
preBlock.appendChild(copyButton);
});
var clipboard = new ClipboardJS('.copy-code-btn');
clipboard.on('success', function(e) {
e.clearSelection();
var originalText = e.trigger.textContent;
e.trigger.textContent = 'Copied!';
e.trigger.style.backgroundColor = '#46b450';
setTimeout(function() {
e.trigger.textContent = originalText;
e.trigger.style.backgroundColor = '#007cba';
}, 2000);
});
clipboard.on('error', function(e) {
console.error('Copy failed:', e.action);
alert('Copy failed. Please select the text manually and press Ctrl+C.');
});
});
Code Explanation & Optimizations
- Selector Adjustment: The selector
.single-content pretargets code blocks. Ensure this matches your theme's container class for post content. - Pure JavaScript: The code does not rely on jQuery for better compatibility.
- User Experience: The button provides visual feedback (text and color change) upon successful copy, then reverts after 2 seconds.
- Error Handling: If copying fails, an error is logged to the console and a user-friendly alert is shown.
Step 3: Testing
After adding the code:
- Clear your browser cache and refresh the page (Ctrl+F5 or Cmd+Shift+R).
- Open a post containing a highlighted code block.
- Verify that a "Copy Code" button appears in the top-right corner of each block.
- Click the button to test the copy functionality and feedback.
If the button does not appear or the function fails, open your browser's Developer Tools (F12) and check the Console tab for JavaScript errors. Common issues include incorrect selectors or file paths.