WordPress ショートコードを作って使ってみた
いくつか WordPress のショートコードを作ってみました.
hello ショートコード
Hello, world! と表示されるショートコードです.
php コード
functions.php
/** * hello world */ function helloFunc() { return "<p><strong>Hello, world!</strong></p>"; } add_shortcode('hello', 'helloFunc');
投稿
[hello]
結果
Hello, world!
code ショートコード
コードを html 用に変換して出力します.(不等号などを置換)
php コード
functions.php
/** * code */ function codeFunc($attr, $content = null) { $content = htmlspecialchars( $content ); return $content; } add_shortcode('code', 'codeFunc');
投稿
[code] #include <stdio.h> int main() { printf("hello, world!\n"); return 0; } [/code]
結果
#include <stdio.h> int main() { printf("hello, world!\n"); return 0; }
custom ショートコード
カスタムフィールドの内容を出力します. 引数として name(カスタムフィールド名)と index(同名カスタムフィールドが複数ある際のインデックス. 省略時は0)を受け取ります.
php コード
functions.php
/** * custom */ function customFunc($attr) { extract(shortcode_atts(array( 'name' => '', 'index' => 0 ), $attr)); if ($name == '') return ''; $values = post_custom($name); if (is_string($values)) { return $values; } else if (is_array($values)) { return $values[ $index ]; } else { return "#"; } } add_shortcode('custom', 'customFunc');
投稿
<h4>demolink</h4> <ul> <li>[custom name="demo_link"]</li> <li>[custom name="demo_link" index="0"]</li> <li>[custom name="demo_link" index="1"]</li> </ul>
結果
demolink
- http://tmlife.net
- http://tmlife.net
- http://google.com
link ショートコード
リンク(a タグ)を出力します. 引数として href(リンク先), コンテンツとして表示テキスト(省略時はhref先のtitle)を受け取ります.
php コード
functions.php
/** * link */ function linkFunc($attr, $content=null) { extract(shortcode_atts(array( 'href' => '#' ), $attr)); if ($content == null) { $html = file_get_contents($href); if (preg_match("/<title>(.*?)<\/title>/i", $html, $matches)) { $content = $matches[1]; } else { $content = $href; } } return '<a href="' . $href . '">' . $content . '</a>'; } add_shortcode('link', 'linkFunc');
投稿
<ul> <li>[link href="http://google.com"]</li> <li>[link href="http://twitter.com/#!/phi_jp"]</li> <li>[link href="http://tmlife.net"]</li> </ul>
結果
Plugin
上記のコードを簡単に導入できるようプラグイン化してみました. よかったら使ってみてください.
下記のリンクをクリックすると tmshortcode.zip ファイルがダウンロードされるので通常のプラグインと同じように, WordPress 管理画面の “プラグイン” → “新規追加” → “アップロード” で “tmshortcode.zip” をインストールしてください.