Theme & Front End JavaScript Intermediate

Add Copy Buttons to Code Blocks

Add a "Copy" button to every code block in your posts, so readers can copy code with one click.

Tested on WordPress 7.1 No plugin needed Updated
script.js 29 lines
document.addEventListener( 'DOMContentLoaded', () => {
	document.querySelectorAll( 'pre > code' ).forEach( ( code ) => {
		const pre = code.parentElement;
		if ( pre.querySelector( '.nahnu-copy' ) ) {
			return;
		}

		const button = document.createElement( 'button' );
		button.type = 'button';
		button.className = 'nahnu-copy';
		button.textContent = 'Copy';
		button.style.cssText = 'position:absolute;top:8px;right:8px;padding:4px 10px;border:0;border-radius:6px;background:#6F58CA;color:#fff;font:600 12px/1.4 system-ui,sans-serif;cursor:pointer';

		button.addEventListener( 'click', async () => {
			try {
				await navigator.clipboard.writeText( code.innerText );
				button.textContent = 'Copied!';
			} catch ( error ) {
				button.textContent = 'Press Ctrl+C';
			}
			setTimeout( () => {
				button.textContent = 'Copy';
			}, 2000 );
		} );

		pre.style.position = 'relative';
		pre.appendChild( button );
	} );
} );

Where to add this

Recommended A code snippets plugin As a JavaScript snippet set to load in the footer.
Child theme Save it as a .js file and load it with wp_enqueue_script() from functions.php.
Page builder Your builder's custom code area, set to load in the footer.

Selecting code by hand is fiddly and often misses a line or grabs extra text. A copy button on each code block makes tutorials much easier to follow.

How it works

The script finds every <code> inside a <pre>, which is how the Code block, the Preformatted block and most syntax highlighters mark up code. It adds a small button in the top-right corner of each one.

Clicking copies the code’s text with the Clipboard API and shows “Copied!” for two seconds. If the browser blocks clipboard access, the button tells the reader to use Ctrl+C instead.

Things to watch

  • The Clipboard API only works on HTTPS pages.
  • Some code highlighting plugins add their own copy button. Use one or the other.

How to test it

Add a Code block to a post and view it. A Copy button should appear in its corner; clicking it should copy the code.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only