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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.