Copy Button on Code Blocks
Adds a "Copy" button to every code block in your posts so readers can copy commands and code samples with one click.
Opens WPIDE on
Code
(function () {
if (!navigator.clipboard) {
return;
}
document.querySelectorAll('.entry-content pre, .wp-block-post-content pre, .wp-block-code').forEach(function (block) {
if (block.tagName !== 'PRE') {
return;
}
var button = document.createElement('button');
button.type = 'button';
button.className = 'wpide-copy-code';
button.textContent = 'Copy';
button.style.cssText = 'position:absolute;top:.5em;right:.5em;padding:.2em .6em;font-size:12px;cursor:pointer;';
if (getComputedStyle(block).position === 'static') {
block.style.position = 'relative';
}
button.addEventListener('click', function () {
var code = block.querySelector('code') || block;
navigator.clipboard.writeText(code.innerText.replace(/\n?Copied!$|\n?Copy$/, '')).then(function () {
button.textContent = 'Copied!';
setTimeout(function () {
button.textContent = 'Copy';
}, 2000);
});
});
block.appendChild(button);
});
})();
Notes
The button appears on pre elements inside the content; style it with the .wpide-copy-code class.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.