How To Enhance Your Code Blocks with a Copy Button in WordPress 📌

Estimated Reading Time: 2 min

Rate this post

If you frequently share code snippets blocks on your WordPress blog, adding a “Copy Code” button can improve user experience. This guide will help you integrate a simple JavaScript solution to enable a one-click copy feature for your code blocks.

Why Add a Copy Button?

  • Makes it easy for readers to copy code snippets.
  • Enhances UX with visual feedback.
  • Works seamlessly with WordPress block editor (.wp-block-code).

Implementation Steps:

1️⃣ Add the following JavaScript snippet to your WordPress theme (inside a custom JavaScript file or the theme’s footer section):

<script>
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.wp-block-code').forEach(function(block) {
        const codeElement = block.querySelector('code');
        if (!codeElement) return;

        const button = document.createElement('button');
        button.textContent = 'Copy Code';
        button.className = 'copy-code-btn';

        button.style.cssText = `
            position: absolute;
            top: 8px;
            right: 8px;
            padding: 6px 10px;
            font-size: 12px;
            background-color: #0073e6;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.2s ease-in-out;
            box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.2);
        `;

        button.addEventListener('mouseenter', () => button.style.backgroundColor = '#005bb5');
        button.addEventListener('mouseleave', () => button.style.backgroundColor = '#0073e6');

        button.addEventListener('click', async function() {
            try {
                await navigator.clipboard.writeText(codeElement.innerText);
                button.textContent = 'Copied!';
                button.style.backgroundColor = '#28a745';

                setTimeout(() => {
                    button.textContent = 'Copy Code';
                    button.style.backgroundColor = '#0073e6';
                }, 2000);
            } catch (err) {
                console.error('Failed to copy text:', err);
                button.textContent = 'Error!';
                button.style.backgroundColor = '#dc3545';

                setTimeout(() => {
                    button.textContent = 'Copy Code';
                    button.style.backgroundColor = '#0073e6';
                }, 2000);
            }
        });

        block.style.position = 'relative';
        block.insertBefore(button, codeElement);
    });

    document.querySelectorAll('.wp-block-code pre').forEach(pre => {
        pre.style.color = '#fff';
        pre.style.padding = '12px';
        pre.style.borderRadius = '5px';
        pre.style.backgroundColor = '#282c34';
        pre.style.overflowX = 'auto';
    });
});
</script>

2️⃣ Save the changes and test it by adding a Code Block in WordPress with some sample code.


Final Result:

With this script, every code blocks will have a “Copy Code” button, making it easier for readers to copy and paste code.

🔹 Have any questions? Drop them in the comments! 💬


Photo of author

Flora

How To Enhance Your Code Blocks with a Copy Button in WordPress 📌

Published

I am Flora, the publisher and founder of *Be-Smart*, a platform dedicated to sharing insights and inspiration for living a fulfilling life. With a strong background in the web, my goal is to empower people to genuinely recognize and celebrate admirable actions big or small in themselves and others.

Leave a Comment