google-code-prettifyの設置でgoogle-code-prettifyを利用できるようにしました。
ただ、毎回<pre class="prettyprint linenums">
って書くのは面倒なのでショートコード[code]~[/code]
で利用できるようにします。
こうしておけば、SyntaxHighlighterに変えようと思えば、出力するタグを変えれば対応できますからね。
ショートコード[code]の定義
利用できる引数は以下になります。
- linenums
-
行番号の開始番号
0:行番号を表示しない
未設定:行番号を1から表示する - lang
-
ソースコードの言語
未設定:言語を設定しない - convert
-
文字参照の要否
true:文字参照処理を行う
未設定:strip_tags関数を利用した自動判定
/** * google-code-prettifyを利用するショートコード */ function shortcode_code( $atts, $content = null ) { // 引数の初期値 $defaults = array( 'linenums' => '1', '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' );
ショートコードの実行
単純に先述のショートコードだけではthe_content
メソッドに対し、「自動で<p>
タグを追加する」autop
のフィルターが設定されています。
そのため、<pre>
タグ内のソースコードに対し、<p>
タグや、<br />
タグが追加されてしまい、意図した結果が得られません。
そこで、wpautop
のフィルターの前にショートコードの実行をする必要があります。
/** * フィルターより前にショートコードを実行させる */ 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 );