# 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.

- Type: JavaScript
- Runs: Site-wide footer
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: code, copy, clipboard
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/copy-button-for-code-blocks/

## Code

```javascript
(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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Copy Button on Code Blocks" in its snippet library and add it in one click; or create a new JavaScript snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
