wordpress
WordPressでカスタムコードを登録・挿入するfunction.phpコード改
最終更新日: 2025年3月1日
前回のコードではprefixを指定したwp-configが使用の前提で、汎用性に欠ける(さくらサーバーでインストールしたWPとDBなら間違いない)。
そもそもprefix設定が大きな意味を持つかどうかというとセキュリティ上はほぼ意味がない。
そこで汎用性を高めるために、非prefix依存のコードを作った。ただしこれもGutenbergでは投稿画面でコードのメニューボタンなどが表示されないので、旧tinyMCEでの投稿エディタ画面での利用可能。
function create_custom_code_table() {
global $wpdb;
// 固定テーブル名(プレフィックスを使わずに)
$table_name = 'custom_codes';
// テーブル作成に必要な文字セットを取得
$charset_collate = $wpdb->get_charset_collate();
// SQL文でテーブルを作成
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
code_title text NOT NULL,
code_text longtext NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
// テーブル作成
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// エラーチェック
if ($wpdb->last_error) {
error_log('Database Error during table creation: ' . $wpdb->last_error);
} else {
error_log('Table successfully created or already exists: ' . $table_name);
}
}
// WordPressが完全に初期化された後にテーブル作成を実行
add_action('init', 'create_custom_code_table');
// 管理画面にカスタムコードメニューを追加
function custom_code_menu() {
add_menu_page(
'カスタムコード管理', // ページタイトル
'カスタムコード', // メニュー名
'manage_options', // 権限
'custom-code-management', // メニューURL
'custom_code_management_page', // コールバック関数
'dashicons-editor-code', // アイコン
100 // 表示位置
);
}
add_action('admin_menu', 'custom_code_menu');
// 管理ページの内容
function custom_code_management_page() {
global $wpdb;
$table_name = 'custom_codes'; // プレフィックスなしのテーブル名
// 登録処理
if (isset($_POST['submit_code'])) {
$code_title = sanitize_text_field($_POST['code_title']);
$code_text = wp_kses_post($_POST['code_text']);
if (!empty($code_title) && !empty($code_text)) {
$wpdb->insert(
$table_name,
['code_title' => $code_title, 'code_text' => $code_text]
);
echo '<div class="updated"><p>コードを登録しました。</p></div>';
} else {
echo '<div class="error"><p>すべてのフィールドを入力してください。</p></div>';
}
}
// 削除処理
if (isset($_GET['delete_id'])) {
$wpdb->delete($table_name, ['id' => intval($_GET['delete_id'])]);
echo '<div class="updated"><p>コードを削除しました。</p></div>';
}
// 登録されたカスタムコードを表示
$codes = $wpdb->get_results("SELECT * FROM $table_name");
echo '<div class="wrap">';
echo '<h1>カスタムコード管理</h1>';
echo '<form method="POST">';
echo '<table class="form-table">';
echo '<tr><th><label for="code_title">タイトル</label></th><td><input type="text" name="code_title" id="code_title" class="regular-text"></td></tr>';
echo '<tr><th><label for="code_text">コード</label></th><td><textarea name="code_text" id="code_text" class="large-text" rows="5"></textarea></td></tr>';
echo '</table>';
echo '<p><input type="submit" name="submit_code" class="button button-primary" value="登録"></p>';
echo '</form>';
// 登録されたカスタムコードのリスト表示
if ($codes) {
echo '<h2>登録済みコード</h2>';
echo '<table class="widefat">';
echo '<thead><tr><th>タイトル</th><th>コード</th><th>操作</th></tr></thead><tbody>';
foreach ($codes as $code) {
echo '<tr>';
echo '<td>' . esc_html($code->code_title) . '</td>';
echo '<td><code>' . esc_textarea($code->code_text) . '</code></td>';
echo '<td><a href="?page=custom-code-management&delete_id=' . intval($code->id) . '" class="button button-secondary">削除</a></td>';
echo '</tr>';
}
echo '</tbody></table>';
}
echo '</div>';
}
// 投稿編集画面にカスタムコード挿入ボタンを追加
function add_custom_code_button() {
global $post;
// 編集画面でのみ表示
if (get_post_type($post) === 'post') {
?>
<button type="button" class="button" id="insert_custom_code">カスタムコード挿入</button>
<div id="custom-code-list" style="display:none;">
<?php
global $wpdb;
$table_name = 'custom_codes';
$codes = $wpdb->get_results("SELECT * FROM $table_name");
foreach ($codes as $code) {
echo '<button class="insert-code button" style="margin:0 5px 10px 5px" data-code="' . esc_attr($code->code_text) . '">' . esc_html($code->code_title) . '</button>';
}
?>
</div>
<script>
document.getElementById('insert_custom_code').addEventListener('click', function() {
var list = document.getElementById('custom-code-list');
list.style.display = (list.style.display === 'none') ? 'flex' : 'none';
});
// コード挿入処理
var codeButtons = document.querySelectorAll('.insert-code');
codeButtons.forEach(function(button) {
button.addEventListener('click', function(e) {
e.preventDefault();
var code = this.getAttribute('data-code');
tinymce.activeEditor.insertContent(code); // TinyMCEエディタに挿入
document.getElementById('custom-code-list').style.display = 'none'; // リストを非表示
});
});
</script>
<?php
}
}
add_action('edit_form_after_editor', 'add_custom_code_button');
取り急ぎprefix依存しない旧エディタ版。
Gutenbergで使うには編集画面に呼び出したボタン類をjavaで埋め込まないといけないが、それもおいおい作ってみることにするが、とりま当方で使うにはTinyMCEのこれで充分かな。
シェアとか調べたわ
結論から言えば、Gutenbergは要らない。要るのはGutenbergで始めて育った(?)人。
そのロジック
- 普通にhtml/CSS実装できる人ならあんな仰々しいブロックエディタ要らない。コーダー・開発者なら、んなモン使うより普通にコード打つ。「直観的」が売りなGutenbergだが、それはすなわち投稿に用いるタグについてインラインでスタイル書くってことだろ(Gutebergムリな者の思い込みかもしれん)。
- 一般の投稿者なら普通のブログやWord文章的なノリで書くから「解りやすさ」「単純さ」が重要。例えばクライアント要望で定型のコードが要るならその単純なものへ定型タグを追加できれば良いわけで、Gutenbergである必要は微塵もない。
- 結局必要とするのはなんとなくコーディングまがいのことができる人たちで、気の利かないエディタだとレイアウト崩れなどを起こすインライン記述をやり勝ち。
Gutengergにはタグ(?)の再利用機能があるらしいからそれ使えばいいじゃんて話でもある。
普通に(?)TinyMCEで打って書くに、hrは普通に入れられるし、四角い囲みを使うなら(キータ(雑!)とかに執筆するとき皆使うよな)それこそカスタムコードで登録してボタン一つで挿入して打ち込めれば充分。
なのでカスタムコード登録・挿入をプラグインではなくfunction.php記述で実装するのは、TinyMCE(Gutenberg以外なら行けんかな、要はエディタ画面をJavaで作らなきゃいけそう)で上等。
このコードはさくらサーバーとKAGOYAで動作確認済、なので大概のサーバーで動くんじゃなかろうか。
追記
後日作ったほかのコード関数と衝突してしまったのと、挿入ボタン位置が長い投稿の場合スクロールで流れることを修正した。
TinyMCEに差し込むのgutenbergより容易とはいっても何かと不都合がでる場合があるので、プラグインやテーマ内コードと衝突して不具合が出る可能性もある。
とりあえず、前回より修正したものをverNo,つけて追記。
//カスタムコード挿入no-prefix ver1.5
function create_custom_code_table() {
global $wpdb;
// 固定テーブル名(プレフィックスを使わずに)
$table_name = 'custom_codes';
// テーブル作成に必要な文字セットを取得
$charset_collate = $wpdb->get_charset_collate();
// SQL文でテーブルを作成
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
code_title text NOT NULL,
code_text longtext NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
// テーブル作成
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// エラーチェック
if ($wpdb->last_error) {
error_log('Database Error during table creation: ' . $wpdb->last_error);
} else {
error_log('Table successfully created or already exists: ' . $table_name);
}
}
add_action('init', 'create_custom_code_table');
function custom_code_menu() {
add_menu_page(
'カスタムコード管理', // ページタイトル
'カスタムコード', // メニュー名
'manage_options', // 権限
'custom-code-management', // メニューURL
'custom_code_management_page', // コールバック関数
'dashicons-editor-code', // アイコン
100 // 表示位置
);
}
add_action('admin_menu', 'custom_code_menu');
function custom_code_management_page() {
global $wpdb;
$table_name = 'custom_codes'; // プレフィックスなしのテーブル名
// 登録処理
if (isset($_POST['submit_code'])) {
$code_title = sanitize_text_field($_POST['code_title']);
$code_text = wp_kses_post($_POST['code_text']);
if (!empty($code_title) && !empty($code_text)) {
$wpdb->insert(
$table_name,
['code_title' => $code_title, 'code_text' => $code_text]
);
echo '<div class="updated"><p>コードを登録しました。</p></div>';
} else {
echo '<div class="error"><p>すべてのフィールドを入力してください。</p></div>';
}
}
// 削除処理
if (isset($_GET['delete_id'])) {
$wpdb->delete($table_name, ['id' => intval($_GET['delete_id'])]);
echo '<div class="updated"><p>コードを削除しました。</p></div>';
}
// 登録されたカスタムコードを表示
$codes = $wpdb->get_results("SELECT * FROM $table_name");
echo '<div class="wrap">';
echo '<h1>カスタムコード管理</h1>';
echo '<form method="POST">';
echo '<table class="form-table">';
echo '<tr><th><label for="code_title">タイトル</label></th><td><input type="text" name="code_title" id="code_title" class="regular-text"></td></tr>';
echo '<tr><th><label for="code_text">コード</label></th><td><textarea name="code_text" id="code_text" class="large-text" rows="5"></textarea></td></tr>';
echo '</table>';
echo '<p><input type="submit" name="submit_code" class="button button-primary" value="登録"></p>';
echo '</form>';
// 登録されたカスタムコードのリスト表示
if ($codes) {
echo '<h2>登録済みコード</h2>';
echo '<table class="widefat">';
echo '<thead><tr><th>タイトル</th><th>コード</th><th>操作</th></tr></thead><tbody>';
foreach ($codes as $code) {
echo '<tr>';
echo '<td>' . esc_html($code->code_title) . '</td>';
echo '<td><code>' . esc_textarea($code->code_text) . '</code></td>';
echo '<td><a href="?page=custom-code-management&delete_id=' . intval($code->id) . '" class="button button-secondary">削除</a></td>';
echo '</tr>';
}
echo '</tbody></table>';
}
echo '</div>';
}
function add_custom_code() {
?>
<script>
document.addEventListener("DOMContentLoaded", function() {
var editorToolbar = document.querySelector("#wp-content-editor-tools");
if (editorToolbar) {
var insertButton = document.createElement("button");
insertButton.innerText = "カスタムコード挿入";
insertButton.className = "button insert-custom-code-button";
insertButton.type = "button";
var codeList = document.createElement("div");
codeList.id = "custom-code-list";
codeList.style.display = "none";
codeList.style.position = "relative";
codeList.style.background = "#fff";
codeList.style.border = "1px solid #ccc";
codeList.style.padding = "10px";
codeList.style.zIndex = "1000";
codeList.style.flexWrap = "wrap";
<?php
global $wpdb;
$table_name = 'custom_codes';
$codes = $wpdb->get_results("SELECT * FROM $table_name");
foreach ($codes as $code) {
// JavaScriptの文字列リテラルとしてエスケープ
$escaped_code = str_replace(array("\r", "\n", '"'), array('\r', '\n', '\"'), $code->code_text);
echo 'var codeButton = document.createElement("button");';
echo 'codeButton.innerText = "' . esc_html($code->code_title) . '";';
echo 'codeButton.className = "button insert-code";';
echo 'codeButton.setAttribute("data-code", "' . esc_attr($escaped_code) . '");';
echo 'codeButton.style.margin = "5px";';
echo 'codeList.appendChild(codeButton);';
}
?>
insertButton.addEventListener("click", function(event) {
event.stopPropagation();
codeList.style.display = (codeList.style.display === "none") ? "flex" : "none";
});
codeList.addEventListener("click", function(event) {
event.stopPropagation();
if (event.target.classList.contains("insert-code")) {
// HTMLエンティティをデコード
var code = event.target.getAttribute("data-code");
var decodedCode = decodeEntities(code);
// HTMLを直接挿入
tinymce.activeEditor.execCommand('mceInsertContent', false, decodedCode);
codeList.style.display = "none";
}
});
document.addEventListener("click", function() {
codeList.style.display = "none";
});
editorToolbar.appendChild(insertButton);
editorToolbar.appendChild(codeList);
}
// HTMLエンティティをデコードする関数
function decodeEntities(encodedString) {
var textArea = document.createElement('textarea');
textArea.innerHTML = encodedString;
return textArea.value;
}
});
</script>
<?php
}
add_action('admin_footer', 'add_custom_code');
再修正
挿入ボタンクリックでページがリロードされる不具合修正。
//カスタムコード挿入no-prefix ver1.6
function create_custom_code_table() {
global $wpdb;
// 固定テーブル名(プレフィックスを使わずに)
$table_name = 'custom_codes';
// テーブル作成に必要な文字セットを取得
$charset_collate = $wpdb->get_charset_collate();
// SQL文でテーブルを作成
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
code_title text NOT NULL,
code_text longtext NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
// テーブル作成
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// エラーチェック
if ($wpdb->last_error) {
error_log('Database Error during table creation: ' . $wpdb->last_error);
} else {
error_log('Table successfully created or already exists: ' . $table_name);
}
}
add_action('init', 'create_custom_code_table');
function custom_code_menu() {
add_menu_page(
'カスタムコード管理', // ページタイトル
'カスタムコード', // メニュー名
'manage_options', // 権限
'custom-code-management', // メニューURL
'custom_code_management_page', // コールバック関数
'dashicons-editor-code', // アイコン
100 // 表示位置
);
}
add_action('admin_menu', 'custom_code_menu');
function custom_code_management_page() {
global $wpdb;
$table_name = 'custom_codes'; // プレフィックスなしのテーブル名
// 登録処理
if (isset($_POST['submit_code'])) {
$code_title = sanitize_text_field($_POST['code_title']);
$code_text = wp_kses_post($_POST['code_text']);
if (!empty($code_title) && !empty($code_text)) {
$wpdb->insert(
$table_name,
['code_title' => $code_title, 'code_text' => $code_text]
);
echo '<div class="updated"><p>コードを登録しました。</p></div>';
} else {
echo '<div class="error"><p>すべてのフィールドを入力してください。</p></div>';
}
}
// 削除処理
if (isset($_GET['delete_id'])) {
$wpdb->delete($table_name, ['id' => intval($_GET['delete_id'])]);
echo '<div class="updated"><p>コードを削除しました。</p></div>';
}
// 登録されたカスタムコードを表示
$codes = $wpdb->get_results("SELECT * FROM $table_name");
echo '<div class="wrap">';
echo '<h1>カスタムコード管理</h1>';
echo '<form method="POST">';
echo '<table class="form-table">';
echo '<tr><th><label for="code_title">タイトル</label></th><td><input type="text" name="code_title" id="code_title" class="regular-text"></td></tr>';
echo '<tr><th><label for="code_text">コード</label></th><td><textarea name="code_text" id="code_text" class="large-text" rows="5"></textarea></td></tr>';
echo '</table>';
echo '<p><input type="submit" name="submit_code" class="button button-primary" value="登録"></p>';
echo '</form>';
// 登録されたカスタムコードのリスト表示
if ($codes) {
echo '<h2>登録済みコード</h2>';
echo '<table class="widefat">';
echo '<thead><tr><th>タイトル</th><th>コード</th><th>操作</th></tr></thead><tbody>';
foreach ($codes as $code) {
echo '<tr>';
echo '<td>' . esc_html($code->code_title) . '</td>';
echo '<td><code>' . esc_textarea($code->code_text) . '</code></td>';
echo '<td><a href="?page=custom-code-management&delete_id=' . intval($code->id) . '" class="button button-secondary">削除</a></td>';
echo '</tr>';
}
echo '</tbody></table>';
}
echo '</div>';
}
function add_custom_code() {
?>
<script>
document.addEventListener("DOMContentLoaded", function() {
var editorToolbar = document.querySelector("#wp-content-editor-tools");
if (editorToolbar) {
var insertButton = document.createElement("button");
insertButton.innerText = "カスタムコード挿入";
insertButton.className = "button insert-custom-code-button";
insertButton.type = "button";
var codeList = document.createElement("div");
codeList.id = "custom-code-list";
codeList.style.display = "none";
codeList.style.position = "relative";
codeList.style.background = "#fff";
codeList.style.border = "1px solid #ccc";
codeList.style.padding = "10px";
codeList.style.zIndex = "1000";
codeList.style.flexWrap = "wrap";
<?php
global $wpdb;
$table_name = 'custom_codes';
$codes = $wpdb->get_results("SELECT * FROM $table_name");
foreach ($codes as $code) {
// JavaScriptの文字列リテラルとしてエスケープ
$escaped_code = str_replace(array("\r", "\n", '"'), array('\r', '\n', '\"'), $code->code_text);
echo 'var codeButton = document.createElement("button");';
echo 'codeButton.innerText = "' . esc_html($code->code_title) . '";';
echo 'codeButton.className = "button insert-code";';
echo 'codeButton.setAttribute("data-code", "' . esc_attr($escaped_code) . '");';
echo 'codeButton.style.margin = "5px";';
echo 'codeList.appendChild(codeButton);';
}
?>
insertButton.addEventListener("click", function(event) {
event.stopPropagation();
codeList.style.display = (codeList.style.display === "none") ? "flex" : "none";
});
codeList.addEventListener("click", function(event) {
event.stopPropagation();
if (event.target.classList.contains("insert-code")) {
// HTMLエンティティをデコード
var code = event.target.getAttribute("data-code");
var decodedCode = decodeEntities(code);
// フォームの送信を阻止してからコードを挿入
event.preventDefault();
tinymce.activeEditor.execCommand('mceInsertContent', false, decodedCode);
codeList.style.display = "none";
}
});
document.addEventListener("click", function() {
codeList.style.display = "none";
});
editorToolbar.appendChild(insertButton);
editorToolbar.appendChild(codeList);
}
// HTMLエンティティをデコードする関数
function decodeEntities(encodedString) {
var textArea = document.createElement('textarea');
textArea.innerHTML = encodedString;
return textArea.value;
}
});
</script>
<?php
}
add_action('admin_footer', 'add_custom_code');