WordPressで文字列を紹介したい時、それが長ければ長いほど読者にストレスを与える可能性があります。
プログラミングのコードを紹介したときなど、読者がボタン1つでコピーできれば便利ですよね。
例えば、以下のように。
<textarea id="input" rows="10" cols="60" placeholder="ここに文章を貼り付けてください"></textarea>
<br>
<button onclick="cleanText()">整形する</button>
<button onclick="copyText()">コピーする</button>
<br>
<textarea id="output" rows="10" cols="60" placeholder="整形後の文章がここに表示されます"></textarea>
<script>
function cleanText() {
let text = document.getElementById("input").value;
// 「あいうえお」を削除
text = text.replace(/あいうえお/g, "");
// 「、」の後にある改行を削除
text = text.replace(/、\s*\n\s*/g, "、");
// 「。」の後は改行を入れる
text = text.replace(/。/g, "。\n");
// 複数の改行を1つにまとめる
text = text.replace(/\n+/g, "\n");
document.getElementById("output").value = text.trim();
}
function copyText() {
const output = document.getElementById("output");
output.select();
document.execCommand("copy");
alert("コピーしました!");
}
</script>
こちらは僕が作ってみた文章整形ツール(需要はありません)なのですが、このコードを紹介しようとしたら、最初以下のように表示されてしまいました。
これは、紹介したいコードがただの文字列として認識されず、一部が実行されてしまっているためです。
コードをただの文字列として表示するためには、それ用にコードを変換する手間が必要になるんですよね。
今回は、「コードを文字列として認識させる変換ツール」と「Wordpressでプラグインを使わず、誰でも簡単にコピーボタンを作成する方法」を紹介します。
コード変換ツール
コードを文字列として表示させるには、「< → <」「> → >」「& → &」などに変換する必要があります。
以下のツールを使うことで、自動で変換することができます。
貼り付けたい生コードを入力
変換後の表示(コピー可能)
こちらのツールのコードは以下です。
僕は、WordpressのカスタムHTMLに貼り付けて使っています。
<style>
.code-box {
background: #f5f5f7;
border: 1px solid #e5e7eb;
border-radius: 12px;
padding: 12px;
font-family: ui-monospace, Menlo, Consolas, monospace;
font-size: 13px;
overflow: auto;
margin-bottom: 16px;
max-height: 500px;
}
.code-box pre {
margin: 12px 0 0 0;
white-space: pre-wrap;
word-break: break-word;
background: #fefefe;
padding: 12px;
border-radius: 8px;
border: 1px solid #e5e7eb;
}
button {
padding: 6px 12px;
border: 1px solid #d1d5db;
border-radius: 8px;
background: #fff;
cursor: pointer;
font-size: 13px;
transition: background 0.2s;
margin-right: 8px;
}
button:hover { background: #f0f0f0; }
button:active { transform: translateY(1px); }
textarea {
width: 100%;
min-height: 120px;
font-family: inherit;
font-size: inherit;
padding: 8px;
border-radius: 6px;
border: 1px solid #d1d5db;
resize: vertical;
margin-bottom: 8px;
}
.button-group {
display: flex;
gap: 8px;
margin-top: 4px;
}
</style>
<div class="code-box">
<h3>貼り付けたい生コードを入力</h3>
<textarea id="raw-code" placeholder="ここにコードを貼り付けてください"></textarea>
<!-- ボタンを横並びに配置 -->
<div class="button-group">
<button id="convert-btn" onclick="convertCode()">自動変換して表示</button>
<button id="copy-btn" onclick="copyConverted()">コピーする</button>
</div>
<h3 style="margin-top:12px;">変換後の表示(コピー可能)</h3>
<pre id="converted-code"></pre>
</div>
<script>
// HTML特殊文字をエスケープ
function escapeHTML(str) {
return str.replace(/&/g,"&")
.replace(/</g,"<")
.replace(/>/g,">");
}
// コード変換表示
function convertCode() {
const raw = document.getElementById("raw-code").value;
const escaped = escapeHTML(raw);
document.getElementById("converted-code").textContent = escaped;
// コピー用ボタンの文言をリセット
const btn = document.getElementById("copy-btn");
btn.textContent = "コピーする";
}
// コピー処理
function copyConverted() {
const code = document.getElementById("converted-code").textContent;
navigator.clipboard.writeText(code).then(() => {
const btn = document.getElementById("copy-btn");
btn.textContent = "コピーしました!";
setTimeout(() => { btn.textContent = "コピーする"; }, 2000);
});
}
</script>
こちらのコードを上のように表示するときも、変換ツールを使わないと全て綺麗に表示されません。
今回も変換ツールを使用してから上のように表示しています。
コードをボタン1つでコピーするツール
では、先ほどのようにコードを紹介したいとき、どのようにすればよいのでしょうか。
ここからは、コードをボタン1つでコピーできるようなコードを紹介します。
コードは以下です。
こちらのコードもWordpressのカスタムHTMLに貼り付けて使っています。
<!-- ✅ 完全版 コピー機能付きコードボックス -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<style>
.code-box {
position: relative;
background: #f5f5f5; /* 全体を薄い灰色に統一 */
border-radius: 12px;
padding: 12px;
font-family: ui-monospace, Menlo, Consolas, monospace;
font-size: 13px;
max-height: 500px;
overflow: auto;
margin-bottom: 16px;
box-shadow: 0 2px 6px rgba(0,0,0,0.05); /* 薄い影 */
}
.code-box pre {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
background: #f5f5f5; /* 背景を統一 */
padding: 12px;
border-radius: 8px;
border: none;
}
.copy-btn {
position: sticky; /* スクロール追従 */
top: 8px;
right: 8px;
float: right;
padding: 6px 12px;
border: none;
border-radius: 999px;
background-color: #8224e3; /* 紫色 */
color: #fff;
font-size: 12px;
cursor: pointer;
z-index: 10;
transition: background 0.2s;
}
.copy-btn:hover { background-color: #6a1fc2; } /* 濃い紫 */
.copy-btn:active { transform: translateY(1px); }
</style>
<div class="code-box">
<button class="copy-btn">
<span class="default">コピー</span>
<span class="done" hidden>コピーしました!</span>
</button>
<pre class="copy-target"><code class="language-html">
<!-- 🔽 ここに紹介したいコードをそのまま貼る -->
ここです!
</code></pre>
</div>
<script>
(() => {
// HTML特殊文字をエスケープ
function escapeHTML(str){
return str.replace(/&/g,"&")
.replace(/</g,"<")
.replace(/>/g,">");
}
// 自動エスケープして表示
document.querySelectorAll(".copy-target").forEach(pre=>{
pre.dataset.raw = pre.textContent;
pre.innerHTML = "<code class='language-html'>" + escapeHTML(pre.textContent) + "</code>";
Prism.highlightElement(pre.querySelector("code")); // Prismでハイライト
});
// コピー処理
async function copyText(text){
if(navigator.clipboard && window.isSecureContext){
await navigator.clipboard.writeText(text);
return true;
} else {
const ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly','');
ta.style.position='fixed';
ta.style.top='-9999px';
document.body.appendChild(ta);
ta.select();
try { document.execCommand('copy'); return true; }
finally { document.body.removeChild(ta); }
}
}
// コピーイベント
document.addEventListener('click', async e=>{
const btn = e.target.closest('.copy-btn');
if(!btn) return;
const box = btn.closest('.code-box');
const target = box.querySelector('.copy-target');
if(!target) return;
const ok = await copyText(target.dataset.raw || "");
const def = btn.querySelector('.default');
const done = btn.querySelector('.done');
if(ok){
def.hidden = true;
done.hidden = false;
setTimeout(()=>{ done.hidden=true; def.hidden=false; },1600);
}
});
})();
</script>
少しわかりづらいですが、コードの中の「ここです!」の部分に紹介したいコード(変換済み)を貼り付けます。
「ここです!」は削除してください。
コード以外にも、コピーさせたい文字があれば、同じように「ここです!」の部分に入力すれば使えます。
こちらのコードをそのまま機能させると、以下のように「ここです!」という文字がコピーできるようになります。
ここです!
まとめ
いかがだったでしょうか?
今回は、コードを文字列として認識させるための変換ツールと、読者が簡単にコードをコピーするためのコピーボタンの作り方を紹介しました。
僕はプログラミング知識がほとんどないので、AIとの壁打ちを何時間も続けてやっと作成できました笑
このコードを改良したい場合は、ChatGPTなどに相談するとボタンの色を変更出来たりします。
お好みでやってみてください。
この記事が少しでも参考になったら嬉しいです。
