WordPress 文章内嵌 Gist 代码

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

继续阅读