1,257 views
この記事は最終更新から 2198日 が経過しています。
1. やりたいこと
WORDPRESSの記事を執筆中に、本文中に table を書きたいことがある。
table, tr, th, tdなどのタグを使って書くのは煩わしいので、Redmineのように | をセパレーターとして簡単に書きたい。
これを実現するための プラグインを作りたい。
2. やってみる
1) プラグインの仕様
仕様は以下の通り。
・ショートコード SimpleTable で挟まれた区間を対象とする。
・本文中の 1行が、テーブル上の 1行となる。
・1行の中の列は、| をセパレーターとして記述する。
2) プラグインのプログラムソースコード
////////////////////////////////////////////////////////////////////////
// 当該プラグインクラスに実体を持たせる。→ __construct()から処理起動
if (class_exists('SimpleTable')) {
$gSimpleTable = new SimpleTable();
}
////////////////////////////////////////////////////////////////////////
class SimpleTable {
//////////////////////////////////////////////////////////////////////
public function __construct() {
//------------------------------------------------------------------
// ショートコードを登録
add_shortcode('SimpleTable', array($this, 'proc_shortcode'));
// テキストウィジェットの中でショートコードを実行可能に設定
add_filter('widget_text', 'do_shortcode');
//------------------------------------------------------------------
// プラグインの有効化、無効化のタイミングでコールさせる。
register_activation_hook( __FILE__, array($this, 'proc_plugin_activate'));
register_deactivation_hook(__FILE__, array($this, 'proc_plugin_deactivate'));
}
//////////////////////////////////////////////////////////////////////
public function proc_plugin_activate(){
// 特に処理なし。
}
//////////////////////////////////////////////////////////////////////
public function proc_plugin_deactivate(){
// 特に処理なし。
}
//////////////////////////////////////////////////////////////////////
public function proc_shortcode( $attr, $content=null ){
// tableのクラス指定があれば取得する。
$table_class = isset($attr['class_'])? $attr['class_'] : '';
// 1行ずつ contentの内容を解析し、テーブルに置き換える。
$trs = '';
$ary_line = explode("<br />", $content);
foreach($ary_line as $line){
$line = trim($line);
if($line == ''){
continue;
}
$ary_td = explode('|', $line);
$tds = '';
foreach($ary_td as $td){
$td = trim($td);
if($td == ''){
continue;
}
$tds .= '<td>'.$td.'</td>';
}
$trs .= '<tr>'.$tds.'</tr>';
}
return <<< EOM
<table class="{$table_class}">
{$trs}
</table>
EOM;
}
} // end of class
3) 使用例
以下のように、
テーブル全体をショートコードで囲み、
| をセパレータとしてテーブルを書く。

すると…
以下のように展開される。
| 1 | AAA |
| 2 | BBB |
| 3 | CCC |
テーブルのスタイルは、ショートコードのパラメーターでクラス名
class_=”xxxxx”
を指定することにより、自由に装飾できる。
3. 所感
・proc_shortcode()の中の処理が手抜き過ぎだな…
→ 後で時間を作って、もうちょっと丁寧に作ろうと思う。
アクセス数(直近7日): ※試験運用中、BOT除外簡易実装済2025-12-09: 1回 2025-12-08: 4回 2025-12-07: 0回 2025-12-06: 0回 2025-12-05: 0回 2025-12-04: 0回 2025-12-03: 1回