# Click-to-Copy Shortcode for Coupon Codes

> Adds a [wpide_copy text="SAVE20"] shortcode that shows the code in a dashed box with a Copy button, and confirms with "Copied!" when clicked.

- Type: PHP
- Runs: Run everywhere
- Category: [Frontend & Design](https://wpide.com/library/category/frontend/)
- Tags: coupon, clipboard, shortcode
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/frontend-copy-text-shortcode/

## Code

```php
add_action( 'wp_enqueue_scripts', function () {
    wp_register_style( 'wpide-copy', false, array(), '1.0' );
    wp_add_inline_style( 'wpide-copy', '.wpide-copy{display:inline-flex;align-items:stretch;border:2px dashed currentColor;border-radius:6px;overflow:hidden;max-width:100%;}.wpide-copy code{padding:.4em .8em;font-size:1.05em;font-weight:700;letter-spacing:.05em;background:none;overflow-wrap:anywhere;}.wpide-copy button{border:0;border-left:2px dashed currentColor;padding:.4em .9em;background:rgba(0,0,0,.05);color:inherit;font:inherit;font-weight:600;cursor:pointer;}.wpide-copy button:hover{background:rgba(0,0,0,.1);}' );

    wp_register_script( 'wpide-copy', false, array(), '1.0', true );
    wp_add_inline_script( 'wpide-copy', "document.addEventListener('click',function(e){var b=e.target.closest&&e.target.closest('.wpide-copy button');if(!b){return;}var t=b.parentNode.querySelector('code').textContent;var done=function(){var o=b.textContent;b.textContent=b.getAttribute('data-done');setTimeout(function(){b.textContent=o;},1800);};if(navigator.clipboard&&window.isSecureContext){navigator.clipboard.writeText(t).then(done);}else{var a=document.createElement('textarea');a.value=t;document.body.appendChild(a);a.select();try{document.execCommand('copy');done();}catch(x){}document.body.removeChild(a);}});" );
} );

add_shortcode( 'wpide_copy', function ( $atts ) {
    $atts = shortcode_atts( array( 'text' => '', 'button' => 'Copy', 'done' => 'Copied!' ), $atts, 'wpide_copy' );

    if ( '' === trim( $atts['text'] ) ) {
        return '';
    }

    wp_enqueue_style( 'wpide-copy' );
    wp_enqueue_script( 'wpide-copy' );

    return sprintf(
        '<span class="wpide-copy"><code>%1$s</code><button type="button" data-done="%3$s" aria-live="polite">%2$s</button></span>',
        esc_html( $atts['text'] ),
        esc_html( $atts['button'] ),
        esc_attr( $atts['done'] )
    );
} );
```

## Notes

Use it for discount codes, commands, account numbers or any short text visitors need to paste elsewhere.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Click-to-Copy Shortcode for Coupon Codes" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
