google-code-prettifyをショートコードで
2014/07/07
プラグイン「Syntax Highlighter」等をインストールする方法もあるが、かなり重たいコードを組んでいるように見え、レスポンシブ時の狭い表示幅で対応しにくくなりそうな気もする。
そこで、js、google-code-prettify を header.php で読み込み。
<script type="text/javascript" src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
この後、function.php に下記のコードを追加。
※参考サイトのコードをほぼそのまま流用した。
参考サイト http://blog.webspace.jp/235
/**
* google-code-prettifyを利用するショートコード
*/
function shortcode_code( $atts, $content = null ) {
// 引数の初期値
$defaults = array(
'linenums' => '0',
'lang' => '',
'convert' => false,
);
$atts = shortcode_atts( $defaults, $atts );
$class = array();
$class[] = 'prettyprint'; // 必須クラス
// linenumsクラスの設定
// linenums="0"の場合にlinenumsを設定しない
if ($atts['linenums']) {
if ($atts['linenums'] > 1) {
$class[] = 'linenums:' . $atts['linenums'];
}
$class[] = 'linenums'; // CSS適用のために付与
}
// 言語の指定
if ($atts['lang']) {
$class[] = 'lang-' . $atts['lang'];
}
// 文字参照への変換の要否
if ($atts['convert']) {
// convert="true"の場合
$convert = true;
} else if ($content != strip_tags($content)) {
// strip_tagsしてみて本文が変化した(タグが存在する)場合
$convert = true;
} else {
$convert = false;
}
if ($convert) {
$content = htmlspecialchars( $content, ENT_QUOTES );
}
// タブを半角スペースに置換
$content = str_replace( "t", " ", $content );
return '<pre class="' . esc_attr(implode($class, ' ')) . '">' . trim($content) . '</pre>';
}
add_shortcode( 'code', 'shortcode_code' );
/**
* フィルターより前にショートコードを実行させる
*/
function code_run_shortcode( $content ) {
global $shortcode_tags;
// ショートコードの登録情報のバックアップ
$orig_shortcode_tags = $shortcode_tags;
// ショートコードの登録情報の削除
remove_all_shortcodes();
// 利用するショートコードの登録
add_shortcode( 'code', 'shortcode_code' );
// 登録したショートコードの実行
$content = do_shortcode( $content );
// ショートコードの登録情報の復元
$shortcode_tags = $orig_shortcode_tags;
return $content;
}
add_filter( 'the_content', 'code_run_shortcode', 7 );
この後、投稿や、固定ページ内で、
[code]〜[/code]
とhtmlやphpコードを囲む。

