Introduction:
Welcome to WebSensePro, and in this WordPress tutorial, we’ll show you how to create a copy to clipboard button. Whether you’re writing code tutorials or want to make it easier for your readers to copy specific text with just a click, this tutorial is for you. The best part? You won’t need to install any additional plugins. We’ll provide you with step-by-step instructions to implement this feature seamlessly.
Step 1:
Preparing Your WordPress Backend
- Log in to your WordPress dashboard.
- To ensure your changes are safe from theme updates, it’s recommended to work with a child theme. If you haven’t already, create and activate a child theme.
- Navigate to “Appearance” and click on “Theme Editor.”
Step 2
Adding the Necessary Code
- In the Theme Editor, select your child theme.
- Open the “Theme Functions” file.
- Add the following code just before the closing
?>
tag:
add_action( 'wp_head', 'copyclipboard' );
function copyclipboard(){
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.11/clipboard.min.js"></script>
<?php
}
add_action( 'wp_footer', 'copyjs' );
function copyjs(){
?>
<script>
var clipboard = new ClipboardJS('.btn');
clipboard.on('success', function (e) {
console.info('Action:', e.action);
console.info('Text:', e.text);
console.info('Trigger:', e.trigger);
});
clipboard.on('error', function (e) {
console.info('Action:', e.action);
console.info('Text:', e.text);
console.info('Trigger:', e.trigger);
});
</script>
<?php
}
- Save your changes by clicking “Update File.”
Step 3:
Creating a Post or Page
- Create a new post or page where you want to add the copy to clipboard button.
- Add your desired content to the post/page. This is the text users will be able to copy.
Step 4:
Adding the Copy to Clipboard Button
- To add the copy to clipboard button, click the “+” button to insert a new block and choose the “Custom HTML” block.
- In the Custom HTML block, insert the following code to create the button:
<button class="btn" data-clipboard-target="#block1">
Copy Code
</button>
- Next, you need to give the content you want to copy an ID. Click on the paragraph block containing the text you want to copy.
Step 5:
Testing Your Copy to Clipboard Button
- Publish your post or page.
- Visit your published post/page and click the “Copy to Clipboard” button. You’ll see the text above it is automatically copied to your clipboard.
Using Elementor (Optional):
If you’re using Elementor to build your content, you can follow a similar process:
- Edit your post with Elementor.
- Add a Text Editor element for the content you want to copy.
- Add an HTML element for the “Copy to Clipboard” button, using the same HTML code as mentioned earlier.
- Give the Text Editor element an ID (e.g., “copy-text”) in the Advanced settings.
4.9/5 - (13 votes)