このブログで実装を進めてきたプラグインについて、以前の記事になりますが、ショートコードを実装しました。
その時に実装した内容はこちらの記事になります。
今回はその時に実装したショートコードプラグインを改造してみます。
まず、前回のコードはちなみに下記のようになっています。
/**
* ショートコード
*/
function samplelistFunction()
{
//データ一覧
$disp_html =<<< EOL
<form action="" method="post">
<h2>データ一覧(ショートコードテスト)</h2>
<div class="wrap">
<table class="wp-list-table widefat striped posts">
<tr>
<th nowrap>ID</th>
<th nowrap>名前</th>
<th nowrap>登録日時</th>
</tr>
EOL;
global $wpdb;
$tbl_name = $wpdb->prefix . 'sample_mst';
$sql = "SELECT * FROM {$tbl_name} ORDER BY id;";
$rows = $wpdb->get_results($sql);
foreach($rows as $row) {
$disp_html .=<<<EOL
<tr>
<td>{$row->id}</td>
<td>{$row->sample_name}</td>
<td>{$row->create_date}</td>
<td>
</tr>
EOL;
}
$disp_html .=<<< EOL
</table>
</div>
</form>
EOL;
return $disp_html;
}
add_shortcode('samplelist', 'samplelistFunction');
上記のコードを投稿側で使用するには、
[samplelist]
のように書きます。
その際に、ショートコードのパラメータ部分を記述し、プログラム側に値として渡す方法を書きます。
[samplelist2 text="TEST"]
プラグイン側の記述も同様にパラメータを受け取るように変更します。
/**
* ショートコード(その2)
*/
function samplelistFunction2($param)
{
$default_param = array(
"text" => "default text"
);
$merged_param = shortcode_atts($default_param, $param);
extract($merged_param);
return esc_html($text);
}
add_shortcode('samplelist2', 'samplelistFunction2');
上記のように実装し、投稿時には
[samplelist2 text="テスト値"]
のようにショートコードを使うことができます。
実際には値を渡す他に、IDやプラグインの挙動を制御するパラメータを渡す用途があるので、設計によって仕様を決めて実装をします。