Instant Copy-to-Clipboard Shortcode for Code Blocks

Why it’s new and useful:
Developers, bloggers, and educators often share code snippets. Adding a “Copy” button next to code blocks improves UX, but most solutions require plugins or heavy JavaScript. This lightweight snippet introduces a [copy_code] shortcode that wraps your code and automatically adds a “Copy” button—no extra plugins required!

1. Add the Snippet to Your Theme’s functions.php or a Custom Plugin

// Add [copy_code] shortcode with copy-to-clipboard button
function wp_copy_code_shortcode($atts, $content = null) {
    $content = trim($content);
    $uid = uniqid('copycode_');
    ob_start();
    ?>
    <div class="copy-code-block" style="position:relative;">
        <button class="copy-btn" data-target="<?php echo esc_attr($uid); ?>" style="position:absolute;top:8px;right:8px;padding:4px 10px;font-size:12px;cursor:pointer;">Copy</button>
        <pre id="<?php echo esc_attr($uid); ?>" style="overflow:auto;background:#f5f5f5;padding:16px;border-radius:5px;"><?php echo esc_html($content); ?></pre>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode('copy_code', 'wp_copy_code_shortcode');

// Enqueue the JS for copy functionality in admin and front-end
add_action('wp_enqueue_scripts', 'wp_copy_code_enqueue_scripts');
add_action('admin_enqueue_scripts', 'wp_copy_code_enqueue_scripts');
function wp_copy_code_enqueue_scripts() {
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('.copy-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                var targetId = btn.getAttribute('data-target');
                var code = document.getElementById(targetId).innerText;
                navigator.clipboard.writeText(code).then(function() {
                    btn.innerText = 'Copied!';
                    setTimeout(function() {
                        btn.innerText = 'Copy';
                    }, 1500);
                });
            });
        });
    });
    </script>
    <?php
}
PHP

2. How to Use

Just wrap your code in [copy_code]…[/copy_code] in any post, page, or custom post type:

[copy_code]
<?php
echo "Hello, World!";
?>
[/copy_code]

3. Features

  • No plugin required (just a snippet!)
  • Works in both admin and front-end
  • Stylish, floating “Copy” button
  • Supports multiple code blocks per page
  • Uses modern navigator.clipboard API
Share this snippet!