Search

How to Add ‘Copy to Clipboard’ Button to Gutenberg Code Block in WordPress Manually

Adding a “Copy to Clipboard” button to a Code block enhances its usability and convenience. This button enables users to effortlessly copy the displayed code with a single click, eliminating the need for manual selection and copying.

This is particularly advantageous for individuals who may not be comfortable with copying code manually, or for those who are browsing on mobile devices where selecting and copying text can be cumbersome.

By incorporating this feature into your website, you provide users with the convenience of effortlessly acquiring the necessary code and seamlessly integrating it into their own projects. This not only enhances efficiency but also reduces the likelihood of errors. Below is an illustration of a Code block that includes syntax highlighting and a “Copy Code” button conveniently located in the top right corner.

In this tutorial, we will walk you through two approaches to seamlessly integrate a copy to clipboard button into your WordPress Code block. The best part? You won’t have to rely on additional third-party plugins. Instead, we’ll show you how to achieve this by adding custom code to your theme file and even guide you in creating your very own custom plugin for this specific functionality. Let’s dive right in and begin!

How to Add ‘Copy to Clipboard’ Button to Gutenberg Code Block in WordPress Manually

Method 1: By Adding a Custom Code in the Theme File

This method is quite straightforward if you have access to your theme’s header.php file. Begin by going to the Appearance  Theme File Editor menu from your WordPress dashboard.

On the Edit Theme page, locate and choose the header.php from the Theme Files list. Then insert the following code just before the closing </head> tag.

<script>
    document.addEventListener('DOMContentLoaded', function() {
    var codeBlocks = document.querySelectorAll('.wp-block-code');
    codeBlocks.forEach(function(block) {
        var code = block.querySelector('code');
        var button = document.createElement('button');
        var buttonText = document.createTextNode('Copy Code');
        button.appendChild(buttonText);
        button.style.cssText = 'position: absolute; top: 0; right: 0; margin: 8px; padding: 4px 8px; font-size: 12px; background-color: #1d8ab3; color: #fff; border: none; border-radius: 4px; cursor: pointer; transition: all 0.2s ease-in-out;';

        button.addEventListener('mouseenter', function() {
            button.style.backgroundColor = '#cce7e8';
        });

        button.addEventListener('mouseleave', function() {
            button.style.backgroundColor = '#1d8ab3';
        });

        button.addEventListener('click', function() {
            var range = document.createRange();
            range.selectNode(code);
            window.getSelection().addRange(range);
            document.execCommand('copy');
            window.getSelection().removeAllRanges();
            button.innerText = 'Copied!';
            button.style.backgroundColor = '#333';
            button.style.color = '#fff';
            setTimeout(function() {
                button.innerText = 'Copy Code';
                button.style.backgroundColor = '#1d8ab3';
                button.style.color = '#fff';
            }, 3000);
        });

        block.style.cssText = 'position: relative;';
        block.insertBefore(button, code);
    });
    var codeTexts = document.querySelectorAll('.wp-block-code pre');
    codeTexts.forEach(function(text) {
        text.style.color = '#fff';
    });
});
</script>

After clicking the Update File button to apply the changes made to the file, you’ll find a “Copy Code” button positioned at the top right corner of your Code block!

Method 2: By Creating a Custom Plugin

If you lack access to your theme’s header file or wish to avoid potential complications and disruptions when changing or updating your theme, then developing a custom plugin may be the more favorable option.

Designing a custom plugin is not particularly challenging. Here are the steps to guide you through the process of creating your very own copy to clipboard button plugin:

Step 1: Create the Plugin Folder

The initial step in crafting a plugin is to establish a dedicated folder to house all of the plugin’s files. While you have the flexibility to choose any folder name, it’s advisable to maintain organization by selecting a name closely associated with your plugin’s purpose. In our case, we’ve chosen ‘copy-code-button’ as the folder name.

Step 2: Create the Plugin Main File

Now, enter the folder you just created, and within it, create a PHP file using your preferred text editor or code editor. Ensure that the PHP file shares the same name as the plugin folder.

Once the file is created, open it, then add the following code:

<?php
/*
Plugin Name: copy-code-button
Plugin URI: https://www.wppagebuilders.com
Description: Custom Plugin for adding custom code
Version: 1.0.0
Author: WPPagebuilders
Author URI: https://www.wppagebuilders.com/
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/

function wpp_copycode() {
    wp_register_script('copy-code-button', plugins_url( '/', __FILE__ ) . 'assets/copycode.js' );
    wp_enqueue_script('copy-code-button');

}
add_action('wp_enqueue_scripts', 'wpp_copycode');

Once the code is added, save the file and proceed to the next step.

Step 3: Create the Script for the Button

The code provided in the preceding step is used to enqueue the copycode.js file, which is a JavaScript file responsible for the script that generates the ‘COPY CODE’ button and enables it to copy the code from the WordPress Code block.

Prior to crafting the copycode.js file, create a folder named ‘assets,’ and then proceed to generate the copycode.js file within this newly created folder.

Now, open up the file you just created and add the following code to it.

document.addEventListener('DOMContentLoaded', function() {
    var codeBlocks = document.querySelectorAll('.wp-block-code');
    codeBlocks.forEach(function(block) {
        var code = block.querySelector('code');
        var button = document.createElement('button');
        var buttonText = document.createTextNode('Copy Code');
        button.appendChild(buttonText);
        button.style.cssText = 'position: absolute; top: 0; right: 0; margin: 8px; padding: 4px 8px; font-size: 12px; background-color: #1d8ab3; color: #fff; border: none; border-radius: 4px; cursor: pointer; transition: all 0.2s ease-in-out;';

        button.addEventListener('mouseenter', function() {
            button.style.backgroundColor = '#cce7e8';
        });

        button.addEventListener('mouseleave', function() {
            button.style.backgroundColor = '#1d8ab3';
        });

        button.addEventListener('click', function() {
            var range = document.createRange();
            range.selectNode(code);
            window.getSelection().addRange(range);
            document.execCommand('copy');
            window.getSelection().removeAllRanges();
            button.innerText = 'Copied!';
            button.style.backgroundColor = '#333';
            button.style.color = '#fff';
            setTimeout(function() {
                button.innerText = 'Copy Code';
                button.style.backgroundColor = '#1d8ab3';
                button.style.color = '#fff';
            }, 3000);
        });

        block.style.cssText = 'position: relative;';
        block.insertBefore(button, code);
    });
    var codeTexts = document.querySelectorAll('.wp-block-code pre');
    codeTexts.forEach(function(text) {
        text.style.color = '#fff';
    });
});

Once you’ve added the code to the file, save the file and continue to the next step.

Step 4: Get the Plugin File Ready and Install it

Now that all the necessary files are prepared, the next step involves compressing the plugin folder into a zip file to make it ready for uploading. You can utilize any archiving tool, as ZIP is the most widely recognized format for archives.

After compressing the folder, you can proceed to upload the plugin to your WordPress site by accessing the Plugin → Add New menu within your WordPress dashboard. Click on the Upload Plugin button, followed by the Choose File button, or simply drag and drop the compressed file into the upload box.

Once the upload is complete, you’ll only need to install and activate the plugin. After activation, you will have the ‘Copy to Clipboard’ button seamlessly integrated into your WordPress Code block.

Update: Custom Code for Copy Code and Open Code in a New Window Button

The following code is designed to place ‘Copy Code’ and ‘Open Code in a New Window’ buttons together at the top-right corner of your WordPress code block. You have two options to implement it:

  1. Use Method 1 and insert the provided code as is.
  2. Opt for Method 2 by incorporating this code into the ‘copycode.js’ file, eliminating the need for the <script></script> tags.”
<script>
    document.addEventListener('DOMContentLoaded', function() {
    var codeBlocks = document.querySelectorAll('.wp-block-code');
    codeBlocks.forEach(function(block) {
        var code = block.querySelector('code');
        var button1 = document.createElement('button');
        var button1Text = document.createTextNode('Copy Code');
        button1.appendChild(button1Text);
        button1.style.cssText = 'position: absolute; top: 0; right: 80px; margin: 8px; padding: 4px 8px; font-size: 12px; background-color: #1d8ab3; color: #fff; border: none; border-radius: 4px; cursor: pointer; transition: all 0.2s ease-in-out;';

        button1.addEventListener('mouseenter', function() {
            button1.style.backgroundColor = '#cce7e8';
        });

        button1.addEventListener('mouseleave', function() {
            button1.style.backgroundColor = '#1d8ab3';
        });

        button1.addEventListener('click', function() {
            var range = document.createRange();
            range.selectNode(code);
            window.getSelection().addRange(range);
            document.execCommand('copy');
            window.getSelection().removeAllRanges();
            button1.innerText = 'Copied!';
            button1.style.backgroundColor = '#333';
            button1.style.color = '#fff';
            setTimeout(function() {
                button1.innerText = 'Copy Code';
                button1.style.backgroundColor = '#1d8ab3';
                button1.style.color = '#fff';
            }, 3000);
        });

        var button2 = document.createElement('button');
        var button2Text = document.createTextNode('Open Code');
        button2.appendChild(button2Text);
        button2.style.cssText = 'position: absolute; top: 0; right: 0; margin: 8px; padding: 4px 8px; font-size: 12px; background-color: #1d8ab3; color: #fff; border: none; border-radius: 4px; cursor: pointer; transition: all 0.2s ease-in-out;';

        button2.addEventListener('mouseenter', function() {
            button2.style.backgroundColor = '#cce7e8';
        });

        button2.addEventListener('mouseleave', function() {
            button2.style.backgroundColor = '#1d8ab3';
        });

        button2.addEventListener('click', function() {
            var codeContent = code.innerHTML;
            var newWindow = window.open('', '_blank', 'width=500,height=300');
            newWindow.document.body.innerHTML = '<pre>' + codeContent + '</pre>';
        });

        block.style.cssText = 'position: relative;';
        block.insertBefore(button1, code);
        block.insertBefore(button2, code);
    });
    var codeTexts = document.querySelectorAll('.wp-block-code pre');
    codeTexts.forEach(function(text) {
        text.style.color = '#fff';
    });
});
</script>

In Conclusion

Code blocks are an essential feature in WordPress for effectively sharing and preserving the integrity of code snippets. The addition of a “Copy to Clipboard” button further streamlines the process, making it more user-friendly and accessible to a wider range of individuals, ultimately enhancing the overall experience for both content creators and consumers.

This page may contain affiliate links, which help support our project. Read our affiliate disclosure.
Hendri Risman

Hendri Risman

Hendri is a WordPress expert and a writer staff at WPPagebuilders. He writes solutions on how to get things fixed in WordPress a lot. Mostly without involving a plugin.
Want to save yearly expense up to $219? why not?

2 thoughts on “How to Add ‘Copy to Clipboard’ Button to Gutenberg Code Block in WordPress Manually”

  1. Your article was exactly what I was looking for and the “COPY CODE” button worked for me, thanks.

    However, in your code window, you have a “Copy to clipboard” icon and a “Open code in a new window” icon. That’s what I would really like to have. Would it be possible for you to update your article, and/or share the code for your “real life” code window?

    Thanks so much!

    Reply
    • Hello George,

      We utilize the Enlighter syntax highlighting plugin for our code window. However, we’ve just made updates to the article, now showcasing a new code feature with an ‘Open Code in a New Window’ button. Please feel free to take a look!

      Reply

Leave a Comment