Adding a copy button to code syntax

How to Add a Copy Button to WordPress Code Syntax Blocks

When displaying code snippets in WordPress, making it easy for users to copy them improves usability and enhances the overall experience. By adding a Copy button to code syntax blocks, visitors can copy code with just a single click—saving them from manually selecting text.

Why Add a Copy Button?

Enhances User Experience – Users can copy code quickly without struggling with text selection.
Improves Readability – Keeps code formatting intact when copying.
Ideal for Developers & Bloggers – Essential for tech blogs, tutorials, and documentation.


Adding the Copy Button to WordPress Code Blocks

Step 1: Insert the Code in functions.php

To add a Copy button to all <pre> (code) blocks, place the following snippet in your theme’s functions.php or use a code snippet plugin like Fluentsnippet.

The example is below in the top right corner.

function add_copy_code_feature() {
?>
<script>
document.addEventListener("DOMContentLoaded", function () {
document.querySelectorAll("pre").forEach((codeBlock) => {
let button = document.createElement("button");
button.innerText = "Copy";
button.classList.add("copy-btn");

button.addEventListener("click", function () {
let code = codeBlock.innerText;
navigator.clipboard.writeText(code).then(() => {
button.innerText = "Copied!";
setTimeout(() => {
button.innerText = "Copy";
}, 2000);
});
});

codeBlock.style.position = "relative";
codeBlock.appendChild(button);
});
});
</script>

<style>
.copy-btn {
position: absolute;
top: 10px;
right: 10px;
background: #333;
color: white;
border: none;
padding: 5px 10px;
font-size: 12px;
cursor: pointer;
border-radius: 4px;
opacity: 0.8;
transition: opacity 0.3s, background 0.3s;
}

.copy-btn:hover {
background: #555;
opacity: 1;
}
</style>
<?php
}
add_action('wp_footer', 'add_copy_code_feature');

How It Works

1️⃣ This JavaScript code finds all <pre> blocks and appends a Copy button to them.
2️⃣ When the button is clicked, the code inside the block is copied to the clipboard.
3️⃣ The button temporarily changes to “Copied!” before resetting back to “Copy” after 2 seconds.
4️⃣ The CSS styles the button, positioning it at the top-right corner of the code block.


Final Thoughts

Adding a Copy button to your WordPress code blocks makes it easier for users to copy and use your code snippets. Whether you’re running a tech blog, developer documentation, or tutorial site, this feature enhances accessibility and user experience.

Notes:

Wp Scriptly

These scripts, CSS styles, and plugins are designed to work best with minimal interference from themes or other plugins. If conflicts arise, adjustments may be needed.
Please note that they must be used as is.”

Let me know if you’d like any further refinements!

Wp Scriptly

Was this information helpful?

Comments: