{"id":46701,"date":"2026-10-10T19:45:09","date_gmt":"2026-10-10T19:45:09","guid":{"rendered":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/?p=46701"},"modified":"2026-10-11T18:02:31","modified_gmt":"2026-10-11T18:02:31","slug":"copy-button-code-block-wordpress","status":"publish","type":"post","link":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/copy-button-code-block-wordpress\/","title":{"rendered":"Add a Copy Button to Every Code Block in WordPress"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">If you publish snippets in WordPress, you probably want a Copy button on every core Code block. Readers can then grab the code without dragging a selection across the lines and missing the last one. Core doesn&#8217;t include that button, and most plugins that add one also bring in a syntax highlighter you may not want.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This small plugin adds a <strong>Copy<\/strong> button to the top-right corner of every core Code block (<code>pre.wp-block-code<\/code>) on the front end. When clicked, the button copies the code, changes to <strong>Copied!<\/strong> for two seconds and then goes back to <strong>Copy<\/strong>. It uses vanilla JavaScript and the asynchronous Clipboard API, with no jQuery. The JS and CSS only load on pages that actually render a Code block. I assumed you want the button on the front end only, not in the editor.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The snippet<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create a folder <code>wp-content\/plugins\/dpc-code-copy\/<\/code> containing three files. The first one is the PHP loader, <code>dpc-code-copy.php<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">&lt;?php\n\/**\n * Plugin Name: DPC Code Block Copy Button\n * Description: Adds a Copy button to every core Code block on the front end.\n * Version:     1.0.0\n *\/\n\ndefined( 'ABSPATH' ) || exit;\n\nconst DPC_CODE_COPY_VERSION = '1.0.0';\n\nadd_action( 'init', 'dpc_code_copy_register_assets' );\nfunction dpc_code_copy_register_assets(): void {\n\twp_register_script(\n\t\t'dpc-code-copy',\n\t\tplugins_url( 'copy.js', __FILE__ ),\n\t\tarray(),\n\t\tDPC_CODE_COPY_VERSION,\n\t\tarray(\n\t\t\t'in_footer' =&gt; true,\n\t\t\t'strategy'  =&gt; 'defer',\n\t\t)\n\t);\n\n\twp_add_inline_script(\n\t\t'dpc-code-copy',\n\t\t'window.dpcCodeCopy = ' . wp_json_encode(\n\t\t\tarray(\n\t\t\t\t'copy'   =&gt; __( 'Copy', 'dpc-code-copy' ),\n\t\t\t\t'copied' =&gt; __( 'Copied!', 'dpc-code-copy' ),\n\t\t\t\t'failed' =&gt; __( 'Copy failed', 'dpc-code-copy' ),\n\t\t\t)\n\t\t) . ';',\n\t\t'before'\n\t);\n\n\twp_register_style(\n\t\t'dpc-code-copy',\n\t\tplugins_url( 'copy.css', __FILE__ ),\n\t\tarray(),\n\t\tDPC_CODE_COPY_VERSION\n\t);\n}\n\n\/\/ Enqueue only when a core Code block is actually rendered.\nadd_filter( 'render_block_core\/code', 'dpc_code_copy_enqueue_on_render' );\nfunction dpc_code_copy_enqueue_on_render( string $block_content ): string {\n\tif ( ! is_admin() ) {\n\t\twp_enqueue_script( 'dpc-code-copy' );\n\t\twp_enqueue_style( 'dpc-code-copy' );\n\t}\n\n\treturn $block_content;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Next, <code>copy.js<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"js\" class=\"language-js\">( () =&gt; {\n\tconst labels = Object.assign(\n\t\t{ copy: 'Copy', copied: 'Copied!', failed: 'Copy failed' },\n\t\twindow.dpcCodeCopy || {}\n\t);\n\n\t\/\/ The Clipboard API only exists on HTTPS (and localhost).\n\tif ( ! window.isSecureContext || ! navigator.clipboard ) {\n\t\treturn;\n\t}\n\n\tdocument.querySelectorAll( 'pre.wp-block-code' ).forEach( ( pre ) =&gt; {\n\t\tconst code = pre.querySelector( 'code' );\n\n\t\tif ( ! code || pre.querySelector( ':scope &gt; .dpc-code-copy' ) ) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst button = document.createElement( 'button' );\n\t\tbutton.type = 'button';\n\t\tbutton.className = 'dpc-code-copy';\n\t\tbutton.textContent = labels.copy;\n\t\tbutton.setAttribute( 'aria-live', 'polite' );\n\n\t\tlet timer;\n\n\t\tbutton.addEventListener( 'click', async () =&gt; {\n\t\t\ttry {\n\t\t\t\tawait navigator.clipboard.writeText( code.innerText );\n\t\t\t\tbutton.textContent = labels.copied;\n\t\t\t} catch {\n\t\t\t\tbutton.textContent = labels.failed;\n\t\t\t}\n\n\t\t\tclearTimeout( timer );\n\t\t\ttimer = setTimeout( () =&gt; {\n\t\t\t\tbutton.textContent = labels.copy;\n\t\t\t}, 2000 );\n\t\t} );\n\n\t\tpre.classList.add( 'dpc-has-copy' );\n\t\tpre.append( button );\n\t} );\n} )();<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, <code>copy.css<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"css\" class=\"language-css\">.wp-block-code.dpc-has-copy {\n\tposition: relative;\n}\n\n.wp-block-code.dpc-has-copy &gt; code {\n\tpadding-right: 5rem;\n}\n\n.dpc-code-copy {\n\tposition: absolute;\n\ttop: 0.5rem;\n\tright: 0.5rem;\n\tpadding: 0.25rem 0.6rem;\n\tfont-family: system-ui, sans-serif;\n\tfont-size: 0.75rem;\n\tline-height: 1.4;\n\tcolor: inherit;\n\tbackground: color-mix(in srgb, currentColor 10%, transparent);\n\tborder: 1px solid color-mix(in srgb, currentColor 30%, transparent);\n\tborder-radius: 4px;\n\tcursor: pointer;\n\topacity: 0.75;\n}\n\n.dpc-code-copy:hover,\n.dpc-code-copy:focus-visible {\n\topacity: 1;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Activate <strong>DPC Code Block Copy Button<\/strong> under Plugins. You can also drop all three files into <code>wp-content\/mu-plugins\/<\/code>, but then you need a loader file there, because WordPress doesn&#8217;t scan subfolders of mu-plugins.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How it works<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The script and style are registered on <code>init<\/code>, not on <code>wp_enqueue_scripts<\/code>. A block theme renders its template before <code>wp_head()<\/code> runs, so the handles have to exist before any block renders.<\/li>\n\n\n<li><code>render_block_core\/code<\/code> runs once for each Code block. Enqueuing there means pages without code load no extra files. In a block theme the stylesheet still prints in the <code>&lt;head&gt;<\/code>. The pattern is the same as in <a href=\"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/load-script-only-when-you-need-it\/\">Load script only when you need it<\/a>.<\/li>\n\n\n<li>The labels go to JS through <code>wp_json_encode()<\/code> in a <code>before<\/code> inline script. They are translatable and safely encoded, and the <code>defer<\/code> strategy stays intact.<\/li>\n\n\n<li>The script finds every <code>pre.wp-block-code<\/code>, adds one button to each, and copies <code>code.innerText<\/code>. <code>innerText<\/code> turns old-style <code>&lt;br&gt;<\/code> line breaks into real newlines.<\/li>\n\n\n<li>One timer per button resets the label after 2000 ms. Clicking again during that time restarts the two seconds instead of stacking timers.<\/li>\n\n\n<li><code>aria-live=\"polite\"<\/code> makes screen readers announce the change to &#8220;Copied!&#8221;.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Customise it<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Change the wording in the <code>__()<\/code> calls, or translate it with the <code>dpc-code-copy<\/code> text domain.<\/li>\n\n\n<li>Change <code>2000<\/code> in <code>copy.js<\/code> to change how long &#8220;Copied!&#8221; stays visible.<\/li>\n\n\n<li>To show the button only on hover, set <code>opacity: 0<\/code> on <code>.dpc-code-copy<\/code> and add <code>.wp-block-code:hover .dpc-code-copy { opacity: 1; }<\/code>. Keep the <code>:focus-visible<\/code> rule so keyboard users can still see it.<\/li>\n\n\n<li>To restyle the button with your theme colours, swap <code>currentColor<\/code> for preset variables such as <code>var(--wp--preset--color--contrast)<\/code>.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Gotchas<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The Clipboard API only works over HTTPS or on <code>localhost<\/code>. On plain HTTP the script adds no buttons, so you never get a button that can&#8217;t do anything.<\/li>\n\n\n<li>The core Code block wraps long lines by default. If your theme switches to <code>white-space: pre<\/code> with horizontal scrolling, the button scrolls along with the content because it sits inside the <code>pre<\/code>.<\/li>\n\n\n<li>Buttons are only added to code that exists when the page loads. Code inserted later by AJAX or infinite scroll needs the loop wrapped in a function you call again.<\/li>\n\n\n<li>An older post on this site, <a href=\"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/copy-code-to-clipboard\/\">Copy code to clipboard<\/a>, covers a general copy button. This one targets the core Code block and loads its files only when needed.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If you&#8217;d rather not create a plugin folder, <a href=\"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/dplugins.com\/downloads\/scripts-organizer\/\">Scripts Organizer<\/a> lets you add the JS and CSS as snippets from inside WordPress.<\/p>\n\n","protected":false},"excerpt":{"rendered":"<p>Add a Copy button to every core Code block in a WordPress block theme. Vanilla JS, top-right corner, shows Copied! for two seconds, loads only when needed.<\/p>\n","protected":false},"author":1,"featured_media":46702,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"slim_seo":{"title":"Add a Copy Button to Every Code Block in WordPress","description":"Add a Copy button to every core Code block in a WordPress block theme. Vanilla JS, top-right corner, shows Copied! for two seconds, loads only when needed."},"_slim_seo_primary_term_category":0,"_slim_seo_primary_term_post_tag":0,"footnotes":""},"categories":[133,3],"tags":[201,202,200,121,203],"dpc_library":[204],"class_list":["post-46701","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-themes","category-wordpress","tag-block-theme","tag-clipboard","tag-code-block","tag-gutenberg","tag-javascript"],"_links":{"self":[{"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/posts\/46701","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/comments?post=46701"}],"version-history":[{"count":1,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/posts\/46701\/revisions"}],"predecessor-version":[{"id":46703,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/posts\/46701\/revisions\/46703"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/media\/46702"}],"wp:attachment":[{"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/media?parent=46701"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/categories?post=46701"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/tags?post=46701"},{"taxonomy":"dpc_library","embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/dpc_library?post=46701"}],"curies":[{"name":"wp","href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/api.w.org\/{rel}","templated":true}]}}