WordPress 内嵌 Gist 链接的方法很简单,将以下代码添加到当前主题的 functions.php 文件中:

/*
 * Embed gists with a URL in post article
 */
function dangopress_embed_gist($matches, $attr, $url, $rawattr)
{
    $embed = sprintf(
        '<script src="https://gist.github.com/%1$s.js%2$s"></script>',
        esc_attr($matches[1]),
        esc_attr($matches[2])
    );

    return apply_filters('dangopress_embed_gist', $embed, $matches, $attr, $url, $rawattr);
}
wp_embed_register_handler('gist', '#https?://gist\.github\.com(?:/[a-z0-9-]+)?/([a-z0-9]+)(\?file=.*)?#i', 'dangopress_embed_gist');

在上面的代码中,我们注册了 Gist 链接的处理方法 dangopress_embed_gist。当我们拷贝 Gist 链接到编辑框时,会调用改方法生成内嵌内容。

Gist 链接是通过注册过程中,指定的正则表达式匹配的:

#https?://gist\.github\.com(?:/[a-z0-9-]+)?/([a-z0-9]+)(\?file=.*)?#i

它可以匹配下面的任意一种形式:

https://gist.github.com/dangoakachan/443ca6efa9622deb3131   # a full gist url example
https://gist.github.com/443ca6efa9622deb3131                # but user name is optional

# If the gist contains multiple file, use "?file=youfile" to embed only one 
https://gist.github.com/e59891e80652bb209f8e?file=moderate.list  # embed moderate.list only

附上演示:

在自己的主题中试试吧 🙂