使用Prism.js为wordpress添加代码高亮功能

WordPress

prism的优势就不用再细说了,网上一搜索有很多信息。总之就是–轻量,强大。在狂放小栈看到了一个集成可视化编辑器的方法,留个记号,以后备查。

首先去这里定制下载你的prism的js和css文件,然后放到你的主题里。如果想用下文的小工具建议安装Line Numbers和Toolbar两个插件。

到这里你就可以体验强大的高亮功能了,高亮标签是

<pre><code class="languages-语言">代码</code></pre>

当然这样使用起来很不方便,所以在可视化编辑器上添加个按钮是更好的办法。这里使用TinyMCE编辑器。后台插件安装启用后做以下2步工作。

1、打开functions,插入下面的php代码:

//添加代码插入按钮
add_action('admin_init', 'insert_code_button');
function insert_code_button(){
    if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') ) {
            return;
    }
    add_filter( 'mce_external_plugins', 'add_highlight_button_plugin' );
    add_filter( 'mce_buttons', 'register_highlight_button' );
}
function register_highlight_button( $buttons ) {
    array_push( $buttons, "|", "highlight" );
    return $buttons;
}
function add_highlight_button_plugin(){
    $plugin_array['highlight'] = get_bloginfo( 'template_url' ) . '/js/highlight.js';
    return $plugin_array;
}

2、在主题js文件夹里面,创建highlight.js文件,代码如下:

(function() {

var boxStyle = '.highlighter-code-box {\
    background: #F1F1F1;\
    position: fixed;\
    left: 50% ;\
    top: 50% ;\
    border: 1px solid #999;\
    width: 460px;\
    height: 465px;\
    margin: -210px 0 0 -230px;\
    line-height: 25px;\
    border-radius: 3px 3px 0 0;\
    z-index:9999;\
}\
.highlighter-code-box-title{\
    height: 25px;\
    background: #444;\
    color: #fff;\
    text-align: center;\
    vertical-align: baseline;\
    font-family: Arial,Verdana;\
    font-size: 11px;\
    \
}\
.highlighter-code-box-toolbar{\
    padding: 5px 15px;\
}\
.highlighter-code-title{\
    width: 430px;\
    height: 30px;\
    font-family: "Courier New", Courier, mono;\
    font-size: 20px;\
    border: 1px solid #DFDFDF;\
    margin: 0 auto;\
    display: block;\
    resize: none;\
}\
.highlighter-code-ln{\
    width: 430px;\
    height: 30px;\
    font-family: "Courier New", Courier, mono;\
    font-size: 17px;\
    border: 1px;\
    margin: 0 auto;\
    display: block;\
    resize: none;\
}\
.highlighter-code-input{\
    width: 430px;\
    height: 310px;\
    font-family: "Courier New", Courier, mono;\
    font-size: 12px;\
    border: 1px solid #DFDFDF;\
    margin: 0 auto;\
    display: block;\
    resize: none;\
}\
.highlighter-code-box-bottombar{\
    text-align: right;\
    padding: 5px 15px;\
}\
.highlighter-code-box-bottombar input{\
    border: 1px solid #BBB;\
    margin: 0;\
    padding: 0 0 1px;\
    font-weight: bold;\
    font-size: 11px;\
    width: 94px;\
    height: 24px;\
    color: black;\
    cursor: pointer;\
    border-radius: 3px;\
    background-color: #EEE;\
    background-image: -ms-linear-gradient(bottom, #DDD, white);\
    background-image: -moz-linear-gradient(bottom, #DDD, white);\
    background-image: -o-linear-gradient(bottom, #DDD, white);\
    background-image: -webkit-gradient(linear, left bottom, left top, from(#DDD), to(white));\
    background-image: -webkit-linear-gradient(bottom, #DDD, white);\
    background-image: linear-gradient(bottom, #DDD, white);\
}\
.highlighter-code-box-bottombar input:hover{\
    border: 1px solid #555;\
}';

var boxTemplate = '\
<div class="highlighter-code-box-title">插入代码</div>\
<div class="highlighter-code-box-toolbar">\
    <label>语言: <select id="codeLanguage">\
</select>\
</label>\
<textarea id="codeTitle" class="highlighter-code-title" placeholder="输入萌萌哒的标题" ></textarea> \
</div>\
<textarea id="codeInput" class="highlighter-code-input" ></textarea>\
<form name="codeLN" class="highlighter-code-ln">\
<label><input id="codeln" type="checkbox" value="显示行号" name="codeln" checked="checked"/>显示行号\
</label>\
</from>\
<div class="highlighter-code-box-bottombar">\
    <input id="codeCancelButton" type="button" value="取消">\
    <input id="codeInsertButton" type="button" value="插入">\
</div>';

var languages = {  //此处可根据不同高亮插件修改成不同的高亮标签
    Markup:     'markup',
    CSS:     'css',
    Clike:   'clike',
    JavaScript: 'javascript',
    PHP:     'php',
	C:     'c',
	HTTP:     'http',
	Java:     'java',
    Nginx:  'nginx',
    SQL:  'sql',
    None:     'none'
}
var codeBox = {
    create: function() {
        var styleNode = document.createElement('style');
        styleNode.innerHTML = boxStyle;
        document.getElementsByTagName('head')[0].appendChild(styleNode);
        
        this._dom = document.createElement('div');
        this._dom.setAttribute('class' , 'highlighter-code-box');
        this._dom.innerHTML = boxTemplate;
        document.body.appendChild(this._dom);
        this._init = true;
        var that = this;
        var language = this.language = document.getElementById('codeLanguage');
        var codetitle = this.codetitle = document.getElementById('codeTitle');
        var textarea = this.textarea = document.getElementById('codeInput');      
        var codeln = this.textarea = document.getElementById('codeln');
        var cancel = document.getElementById('codeCancelButton');
        var insert = document.getElementById('codeInsertButton');
        var html = '';
        for(var i in languages){
            html += '<option value="' + languages[i] + '">' + i + '</option>';
        }
        language.innerHTML = html;
        cancel.onclick = function(){
            that.hide();
        }
        insert.onclick = function(){
        	   var title = codetitle.value;
            var text = textarea.value;
            var lan = language.value;
            var ln = codeln.checked;
            var label = language.options[language.selectedIndex].innerHTML;
            text = text.replace(/&/g, '&amp;');
            text=text.replace(/</g,'&lt;').replace(/>/g, '&gt;');
           if(!title){
           	if(ln){
           text = '<pre class="line-numbers"><code class="language-' + lan + '">' + text + '</code></pre>';
           }else{
           text = '<pre><code class="language-' + lan + '">' + text + '</code></pre>';
           }
           }else{
           	if(ln){
            text = '<pre class="line-numbers" data-lable="'+ title +'"><code class="language-' + lan + '">' + text + '</code></pre>';
            }else{    	          
            text = '<pre data-lable="'+ title +'"><code class="language-' + lan + '">' + text + '</code></pre>';
            	
            }
            }
            //上面这句也应该根据不同高亮插件修改不同class格式
            that._action && that._action(text);
            that.hide();
            if(localStorage){
                localStorage['lastLanguage'] = lan;
            }
        }
    },
    show: function(action) {
        if (!this._init) {
            this.create();
        }
        this.textarea.value = '';
        this._action = action;
        if(localStorage && localStorage['lastLanguage']){
            this.language.value = localStorage['lastLanguage'];
        }
        this._dom.style.display = 'block';
    },
    hide: function(){
        this._action = null;
        this._dom.style.display = 'none';
    }
};

tinymce.create('tinymce.plugins.highlight', {
    init : function(ed, url) {
        ed.addButton('highlight', {
            title : '代码高亮',
			icon : 'code',
            onclick : function() {
              codeBox.show(function(text){
                ed.selection.setContent(ed.selection.getContent()+text);
              });
            }
        });
    },
    createControl : function(n, cm) {
        return null;
    },
});
tinymce.PluginManager.add('highlight', tinymce.plugins.highlight);

})();

里面的语言根据自己的情况增减。然后在主题的header.php里引用prism.css,footer.php里引用prism.js。

完工。

感谢狂放小栈分享方法。

继续阅读
发表观点
  • 昵称不能为空
  • 邮箱不能为空
  • 还是写点什么卅...