{"id":45496,"date":"2022-05-18T16:11:52","date_gmt":"2022-05-18T16:11:52","guid":{"rendered":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/?p=45496"},"modified":"2026-10-10T19:57:41","modified_gmt":"2026-10-10T19:57:41","slug":"copy-code-to-clipboard","status":"publish","type":"post","link":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/copy-code-to-clipboard\/","title":{"rendered":"Add a Copy to Clipboard Button to WordPress Code Blocks"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Readers of a WordPress tutorial or documentation site copy code all the time, and selecting a long block by hand often misses the first or last line. This snippet adds a <strong>Copy<\/strong> button to every code block on your WordPress site. One click puts the whole block on the clipboard, and the button says <strong>Copied!<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is plain CSS and JavaScript, with no plugin, jQuery or library. It works with the core <strong>Code<\/strong> block and with any <code>&lt;pre&gt;<\/code> your theme or a page builder prints.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The CSS<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"css\" class=\"language-css\">\/* Copy button on code blocks (dpc). *\/\n.dpc-copy {\n\tposition: relative;\n}\n\n.dpc-copy-btn {\n\tposition: absolute;\n\ttop: 0.5em;\n\tright: 0.5em;\n\tpadding: 0.25em 0.6em;\n\tborder: 1px solid currentColor;\n\tborder-radius: 4px;\n\tbackground: rgba(255, 255, 255, 0.9);\n\tcolor: #1e1e1e;\n\tfont: 600 12px\/1.4 system-ui, sans-serif;\n\tcursor: pointer;\n\topacity: 0;\n\ttransition: opacity 0.15s;\n}\n\n.dpc-copy:hover .dpc-copy-btn,\n.dpc-copy-btn:focus-visible,\n.dpc-copy-btn.is-copied {\n\topacity: 1;\n}\n\n@media (hover: none) {\n\t.dpc-copy-btn {\n\t\topacity: 1;\n\t}\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">The JavaScript<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"js\" class=\"language-js\">(function () {\n\tvar LABEL = 'Copy';\n\tvar COPIED = 'Copied!';\n\tvar FAILED = 'Press Ctrl+C';\n\n\tfunction copyText(text) {\n\t\tif (navigator.clipboard &amp;&amp; window.isSecureContext) {\n\t\t\treturn navigator.clipboard.writeText(text);\n\t\t}\n\t\t\/\/ Fallback for plain http:\/\/ sites, where the Clipboard API is not available.\n\t\treturn new Promise(function (resolve, reject) {\n\t\t\tvar area = document.createElement('textarea');\n\t\t\tarea.value = text;\n\t\t\tarea.setAttribute('readonly', '');\n\t\t\tarea.style.position = 'fixed';\n\t\t\tarea.style.opacity = '0';\n\t\t\tdocument.body.appendChild(area);\n\t\t\tarea.select();\n\t\t\tvar ok = false;\n\t\t\ttry {\n\t\t\t\tok = document.execCommand('copy');\n\t\t\t} catch (e) {\n\t\t\t\tok = false;\n\t\t\t}\n\t\t\tdocument.body.removeChild(area);\n\t\t\tif (ok) {\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\treject(new Error('copy failed'));\n\t\t\t}\n\t\t});\n\t}\n\n\tfunction addButton(pre) {\n\t\tif (pre.classList.contains('dpc-copy')) {\n\t\t\treturn;\n\t\t}\n\t\tvar button = document.createElement('button');\n\t\tbutton.type = 'button';\n\t\tbutton.className = 'dpc-copy-btn';\n\t\tbutton.textContent = LABEL;\n\t\tbutton.setAttribute('aria-live', 'polite');\n\n\t\tbutton.addEventListener('click', function () {\n\t\t\tvar code = pre.querySelector('code');\n\t\t\tvar text = code ? code.textContent : Array.prototype.filter.call(pre.childNodes, function (node) {\n\t\t\t\treturn node !== button;\n\t\t\t}).map(function (node) {\n\t\t\t\treturn node.textContent;\n\t\t\t}).join('');\n\n\t\t\tcopyText(text).then(function () {\n\t\t\t\tbutton.textContent = COPIED;\n\t\t\t}, function () {\n\t\t\t\tbutton.textContent = FAILED;\n\t\t\t}).then(function () {\n\t\t\t\tbutton.classList.add('is-copied');\n\t\t\t\tsetTimeout(function () {\n\t\t\t\t\tbutton.textContent = LABEL;\n\t\t\t\t\tbutton.classList.remove('is-copied');\n\t\t\t\t}, 2000);\n\t\t\t});\n\t\t});\n\n\t\tpre.classList.add('dpc-copy');\n\t\tpre.appendChild(button);\n\t}\n\n\tfunction init() {\n\t\tdocument.querySelectorAll('pre').forEach(addButton);\n\t}\n\n\tif (document.readyState === 'loading') {\n\t\tdocument.addEventListener('DOMContentLoaded', init);\n\t} else {\n\t\tinit();\n\t}\n})();<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Add it with Scripts Organizer<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In <a href=\"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/dplugins.com\/downloads\/scripts-organizer\/\">Scripts Organizer<\/a> go to <strong>Code Blocks \u2192 Add New<\/strong> and give the block a name. Set <strong>Trigger location<\/strong> to <strong>Conditions<\/strong> and leave <strong>Template<\/strong> on <strong>All<\/strong>. Under <strong>Script location<\/strong> tick <strong>Header<\/strong> and <strong>Footer<\/strong>.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Header<\/strong>: set <strong>Header Mode<\/strong> to <strong>CSS<\/strong> and paste the CSS.<\/li>\n\n\n<li><strong>Footer<\/strong>: set <strong>Footer Mode<\/strong> to <strong>Javascript<\/strong> and paste the JavaScript.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Publish and enable the block. Scripts Organizer prints Header and Footer code on the front end only with the <strong>Conditions<\/strong> trigger, not with <strong>Everywhere<\/strong>. To load it only on your blog, narrow the <strong>Template<\/strong> condition to posts.<\/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>On page load the script finds every <code>&lt;pre&gt;<\/code>, adds the class <code>dpc-copy<\/code> and appends a <code>&lt;button&gt;<\/code>. The class also stops it from adding a second button.<\/li>\n\n\n<li>The copied text is the <code>textContent<\/code> of the <code>&lt;code&gt;<\/code> inside the <code>&lt;pre&gt;<\/code>, or of the <code>&lt;pre&gt;<\/code> itself without the button. Syntax highlighters that wrap tokens in <code>&lt;span&gt;<\/code>s still give the plain code.<\/li>\n\n\n<li><code>navigator.clipboard.writeText()<\/code> does the copying. It only exists on HTTPS (and <code>localhost<\/code>), so on plain <code>http:\/\/<\/code> the script falls back to a hidden textarea and <code>document.execCommand('copy')<\/code>.<\/li>\n\n\n<li>The button is a real <code>&lt;button&gt;<\/code>: keyboard users can tab to it, and <code>aria-live<\/code> makes screen readers announce <strong>Copied!<\/strong>. It shows on hover, on keyboard focus, and always on touch screens.<\/li>\n\n\n<li>The older version of this post, based on WPJohnny&#8217;s Code Click-to-Copy plugin, copied on a click anywhere in the code, including inline <code>&lt;code&gt;<\/code> in paragraphs, so readers could no longer select part of a block. It also used the deprecated global <code>event<\/code> and an Oxygen colour variable.<\/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>Other labels or language: change <code>LABEL<\/code>, <code>COPIED<\/code> and <code>FAILED<\/code> at the top of the script.<\/li>\n\n\n<li>Only core Code blocks: change <code>querySelectorAll('pre')<\/code> to <code>querySelectorAll('pre.wp-block-code')<\/code>.<\/li>\n\n\n<li>Colours and position: edit <code>.dpc-copy-btn<\/code> in the CSS. Use your theme&#8217;s colour variables there if it has them.<\/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>On a code block that scrolls sideways, the button sits at the top right of the visible box and moves with the content when it scrolls. Wrap long lines with <code>white-space: pre-wrap<\/code> if that bothers you.<\/li>\n\n\n<li>Code added later by JavaScript (tabs, AJAX loading) gets no button. Add <code>window.dpcCopyInit = init;<\/code> above the <code>readyState<\/code> check and call <code>dpcCopyInit()<\/code> after the new content is in the page.<\/li>\n\n\n<li>The script does not load in the block editor; there it would get in the way of editing.<\/li>\n\n<\/ul>\n\n","protected":false},"excerpt":{"rendered":"<p>Add a Copy button to every code block on your WordPress site with plain CSS and JavaScript: Clipboard API, http fallback, keyboard accessible.<\/p>\n","protected":false},"author":1,"featured_media":46735,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"slim_seo":{"title":"Add a Copy to Clipboard Button to WordPress Code Blocks","description":"Add a Copy button to every code block on your WordPress site with plain CSS and JavaScript: Clipboard API, http fallback, keyboard accessible."},"_slim_seo_primary_term_category":0,"_slim_seo_primary_term_post_tag":0,"footnotes":""},"categories":[3],"tags":[],"dpc_library":[204],"class_list":["post-45496","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-wordpress"],"_links":{"self":[{"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/posts\/45496","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=45496"}],"version-history":[{"count":1,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/posts\/45496\/revisions"}],"predecessor-version":[{"id":46734,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/posts\/45496\/revisions\/46734"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/media\/46735"}],"wp:attachment":[{"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/media?parent=45496"}],"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=45496"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/tags?post=45496"},{"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=45496"}],"curies":[{"name":"wp","href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/api.w.org\/{rel}","templated":true}]}}