Easily create a copy code button in WordPress: WPCode!

Today I have a really useful tip for anyone who runs a coding blog, but it's also useful for everyone else: how to add a WordPress codeblock copy button. Code copying is really important for programming blogs because it makes it easy for readers to copy and paste code.

Add a pretty copy button to your WordPress codeblock, and your readers can copy your code with a single click. Isn't that cool? Plus WPCode pluginmakes it really easy to add this functionality, so come along for the ride!

Why do we need a Copy Code button?

 코드 복사 버튼이 없는 코드블럭 형식 참고 이미지
(Basic codeblock format reference image)

In fact, the default codeblock, as shown in the image above, is just text on a pale light blue background. If you want to scrape the text inside that block, you'll have to drag it with your mouse! However, adding a "copy button" to your blog is great for several reasons

  1. Make it easy for readers to copy and paste your code.
  2. It's handy to be able to copy long chunks of code at once.
  3. You'll make fewer mistakes moving code around.
  4. It greatly improves the usability of WordPress codeblocks.

Now, let's get to work implementing the CodeCopy button.

Install the WPCode plugin

First, you'll need to install the plugin, which makes it easy to implement a codeblock copy button. From your WordPress admin page, go to Plugins > Add New Plugin, search for "WPCode", install and activate it.

If you go to the Warp Admin page, you'll see "WPCode" in the top menu, and if you click on it, you'll see the "Add Snippet" submenu. Using this, we're going to implement a Copy Code Block button that will allow us to easily copy and paste code to apply CSS and JavaScript code.

( 플러그인 설치 후 워프 관리자 페이지 화면 )
(Warp Admin page screen after installing the plugin)

Customizing the Copy Code button with CSS

Now we're going to use CSS to create the look of this copy button. First, we'll use a plugin to add this style to the header of the entire site.

  1. In your WordPress admin menu, click Code Snippets > Add Snippet in the left-hand menu or WPCode > Add Snippet at the top.
  2. Click Add Custom Code (New Snippet) or Add Custom Snippet and select CSS Snippet.
  3. Name your snippet "Copy Button Style" (you'll want to name it something that distinguishes it from your other snippets) and paste the code below.
pre {
  position: relative;
}

.copy-button {
  position: absolute;
  top: 5px;
  right: 5px;
  padding: 5px 10px;
  background-color: #f1f1f1f1;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  color: #000000;
  font-size: 14px;
}

.copy-button:hover {
  background-color: #ddd;
}
  1. Select the location as 'Site-wide header' and clip Save Snippet > Activate.

This will apply the 'copy button style' to WordPress codeblocks throughout your site!

Adding code copy functionality with JavaScript

Now it's time to add some JavaScript to make the copy button actually work. This code will implement the functionality of the codeblock copy button. Speaking of JavaScript, all you need to do in the steps above is select a snippet and give it a title. The only thing you need to change is the location: the site-wide footer.

document.addEventListener('DOMContentLoaded', function () {
  const codeBlocks = document.querySelectorAll('pre');

  codeBlocks.forEach(function (block) {
    const copyButton = document.createElement('button');
    copyButton.className = 'copy-button';

    const icon = document.createElement('i');
    icon.className = 'copy-icon';
    icon.textContent = '🗐';

    const text = document.createElement('span');
    text.textContent = ' Copy';

    copyButton.appendChild(icon);
    copyButton.appendChild(text);

    block.appendChild(copyButton);

    copyButton.addEventListener('click', function () {
      const code = block.querySelector('code').innerText;

      navigator.clipboard.writeText(code).then(function () {
        icon.textContent = '✔';
        text.textContent = ' Copied';
        copyButton.disabled = true;

        setTimeout(function () {
          icon.textContent = '🗐';
          text.textContent = ' Copy';
          copyButton.disabled = false;
        }, 2000);
      });
    });
  });
});

Now, open up any post you've already written using the code block and see if you can see the Copy button like below! You should have a nice copy button for every WordPress code block! In the image below, the code block above has a '✔ Copied' mark because we've already copied the code.

코드 복사 붙혀넣기 기능 사용 결과 이미지
(Result of using the copy-paste code feature)

Finalize

It's not as hard as you think, is it? With some code and plugins, you can implement this cool feature without any complicated code modifications. Now your blog readers will be able to easily copy code or text with a single click. Why not add this feature to your blog?

As a side note, if you want to change the size of the text or change the emoji, the code breakdown below should give you a good idea of how to do it.

And what if we wanted to refine the buttons we use in Warp a bit? Attention All: The Secret to Animating Buttons That Stand Out (feat. WordPress) Check out the post to find out how!

# Glossary

  • WPCode plugin: A tool that makes it easy to add code snippets to WordPress.
  • Snippet: A small piece of reusable code.
  • CSSA style language for decorating the look and feel of a webpage.
  • JavaScriptA programming language for adding dynamic functionality to web pages.
  • Codeblocks: A special area to showcase programming code in your blog posts.
  • ClipboardA virtual space on your computer that temporarily stores copied content.

# Code Explained in detail

CSS code commentary

  • pre { position: relative; }: Sets the position of the codeblock relative to each other.
  • .copy-button { ... }Defines the default style for the copy button.
  • position: absolute;Places the : button in an absolute position within the codeblock.
  • top: 5px; right: 5px;button in the upper right corner.
  • padding: 5px 10px;Sets the margin inside the button.
  • background-color: #f1f1f1f1;Sets the button background color.
  • border: none; border-radius: 3px;: Removes the border and rounds the corners.
  • cursor: pointer;: Changes the appearance of the cursor when hovered over.
  • color: #000000; font-size: 14px;: Sets the text color and size.
  • .copy-button:hover { ... }: Defines the style when the button is hovered over.

JavaScript code commenting

  • document.addEventListener('DOMContentLoaded', function () { ... });: Run the script after the page finishes loading.
  • const codeBlocks = document.querySelectorAll('pre');: Select all code blocks within the page.
  • codeBlocks.forEach(function (block) { ... });: iterates over each code block.
  • const copyButton = document.createElement('button');: Creates a copy button element.
  • copyButton.className = 'copy-button';Apply the CSS class to the : button.
  • const icon = document.createElement('i');: Creates an icon element.
  • const text = document.createElement('span');: Creates a text element.
  • copyButton.appendChild(icon); copyButton.appendChild(text);Add an icon and text to the : button.
  • block.appendChild(copyButton);: Add a button to the codeblock.
  • copyButton.addEventListener('click', function () { ... });: Handles button click events.
  • const code = block.querySelector('code').innerText;: Gets the text within the codeblock.
  • navigator.clipboard.writeText(code).then(function () { ... });: Copy the code to the clipboard.
  • icon.textContent = '✔'; text.textContent = ' Copied';: Change the button state after copying is complete.
  • setTimeout(function () { ... }, 2000);: Returns the button state to its original state after 2 seconds.
테리 이모티콘
(Happy coding!)

Similar Posts