WordPressのショートコードネタです。
Gistで書いたコードをブログに表示
させる為のショートコード。最近は特
にGithub関連のビギナー向け記事を見か
けますのでこういうTipsもあわせて使うと
より捗るんじゃないかなと。
必要になったので調べました。ついでにシェアです。
gistに書いたコードを表示させるプラグインをWP Total hacksの開発者さんが既に開発しているんですが、多用しないならこうしたショートコードでもいいかな。
コード
こんな感じでgistをショートコードで表示させます。その為には以下のコードをfunctions.phpに含めます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// [gist id="ID" file="FILE"] | |
function gist_shortcode($atts) { | |
return sprintf( | |
'<script src="https://gist.github.com/%s.js%s"></script>', | |
$atts['id'], | |
$atts['file'] ? '?file=' . $atts['file'] : '' | |
); | |
} add_shortcode('gist','gist_shortcode'); | |
// Remove this function if you don't want autoreplace gist links to shortcodes | |
function gist_shortcode_filter($content) { | |
return preg_replace('/https:\/\/gist.github.com\/([\d]+)[\.js\?]*[\#]*file[=|_]+([\w\.]+)(?![^<]*<\/a>)/i', '[gist id="${1}" file="${2}"]', $content ); | |
} add_filter( 'the_content', 'gist_shortcode_filter', 9); | |
?> |
gistのembedは【https://gist.github.com/IDの数字.js?file=ファイル名】ですので、ショートコードで数字を入れてあげればいいだけですね。
ショートコードは
[gist id="1766997"]
という感じで書けばOKです。シンタックスハイライトは重いから入れたくないよ、って方はgistでいいんじゃないでしょうか。
尚、フレームとかではなく、div要素が読み込まれますので、表示するサイトのCSSで表示に影響が出る場合があります。その際は便宜調整してください。
ちなみに
記事内でショートコードを無効化するには
[[gallery]]
というようにカッコを2重にすれば無効化されます。ショートコードをブログで紹介したいときにご活用下さい。
今日のコードはお馴染みのwp-snippetsです。