Code Copy Block
Adds a [sc_code lang="php"] shortcode that renders a dark syntax-labelled code block with a one-click copy-to-clipboard button.
Module3 parts · by SnipCraft
PHPShortcode
php
<?php
if ( ! function_exists( 'scseed_code_copy_shortcode' ) ) {
function scseed_code_copy_shortcode( $atts, $content = '' ) {
$atts = shortcode_atts( [ 'lang' => '' ], $atts, 'sc_code' );
$lang = esc_html( strtolower( sanitize_key( $atts['lang'] ) ) );
$code = htmlspecialchars( trim( $content ), ENT_QUOTES, 'UTF-8' );
$id = 'scseed-code-' . wp_unique_id();
$out = '<div class="scseed-code-block">';
if ( $lang ) {
$out .= '<span class="scseed-code-lang">' . $lang . '</span>';
}
$out .= '<button class="scseed-code-copy" type="button" data-target="' . esc_attr( $id ) . '" aria-label="' . esc_attr__( 'Copy code', 'default' ) . '">';
$out .= '<span class="scseed-code-copy-label">Copy</span>';
$out .= '</button>';
$out .= '<pre class="scseed-code-pre"><code id="' . esc_attr( $id ) . '">' . $code . '</code></pre>';
$out .= '</div>';
return $out;
}
}
add_shortcode( 'sc_code', 'scseed_code_copy_shortcode' );CSSStyles
css
.scseed-code-block {
position: relative;
margin: 20px 0;
border-radius: 8px;
background: #1e1e2e;
overflow: hidden;
}
.scseed-code-lang {
position: absolute;
top: 10px;
left: 14px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: #6272a4;
}
.scseed-code-copy {
position: absolute;
top: 8px;
right: 10px;
background: rgba(255,255,255,0.08);
border: 1px solid rgba(255,255,255,0.15);
color: #ccc;
border-radius: 4px;
padding: 4px 10px;
font-size: 12px;
cursor: pointer;
transition: background 0.2s;
z-index: 1;
}
.scseed-code-copy:hover { background: rgba(255,255,255,0.16); color: #fff; }
.scseed-code-pre {
margin: 0;
padding: 40px 18px 18px;
overflow-x: auto;
font-size: 14px;
line-height: 1.65;
}
.scseed-code-pre code {
display: block;
color: #cdd6f4;
background: none;
font-family: 'Fira Code', 'Cascadia Code', Consolas, monospace;
white-space: pre;
}JavaScriptScript
js
(function () {
function initCodeCopy() {
document.querySelectorAll('.scseed-code-copy').forEach(function (btn) {
if (btn.dataset.scCopyInit) return;
btn.dataset.scCopyInit = '1';
btn.addEventListener('click', function () {
var targetId = btn.getAttribute('data-target');
var el = targetId ? document.getElementById(targetId) : null;
if (!el) return;
var text = el.textContent || '';
if (!navigator.clipboard || !navigator.clipboard.writeText) return;
navigator.clipboard.writeText(text).then(function () {
var label = btn.querySelector('.scseed-code-copy-label');
if (!label) return;
label.textContent = 'Copied!';
setTimeout(function () { label.textContent = 'Copy'; }, 2000);
});
});
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initCodeCopy);
} else {
initCodeCopy();
}
})();#shortcode#clipboard#developer#code