百度ueditor编辑器很久不更新了,自带的代码高亮插件很丑,刚开始用Highlight.js试了下,代码行数展示比较难搞,最后发现Prism.js真是简洁漂亮又好用,真香~!
官网地址:https://prismjs.com/
先去官网选择自己想要的主题,自定义选择想要支持高亮的代码类型和相关插件。然后把Prism.js和Prism.css下载到网站主题目录下。
在主题js目录下新建一个ueditorconv.js文件,用来转换替换ueditor自带的代码高亮。代码如下:
// ueditorconv.js
jQuery(document).ready(function($){
(function(){
var doc_pre = $('pre');
doc_pre.each(function(){
var class_val = $(this).attr('class');
var class_arr = new Array();
class_arr = class_val.split(';');
class_arr = class_arr['0'].split(':');
var lan_class = 'language-'+class_arr['1'];
var pre_content = '<code class="'+lan_class+'">'+$(this).html()+'</code>';
$(this).html(pre_content);
$(this).attr("class",'line-numbers '+lan_class);
});
})();
});之后编辑functions.php文件,添加如下代码,加载Prism.js、Prism.css和ueditorconv.js文件。
// 引入 prism.js && prism.css
function add_prism_scripts() {
// 如果当前访问的页面是已存在的文章页,且不在指定分类中,则引入 prism.js 包
// -_-! 没办法,为了兼容以前有些文章代码高亮格式,不需要可以去掉排除的分类
if (is_single() && !in_category(array(159,95,115))) {
// Register prism.css file
wp_register_style(
'prismCSS', // handle name for the style
get_template_directory_uri() .
'/css/prism.css' // location of the prism.css file
);
// Register prism.js file
wp_register_script(
'prismJS', // handle name for the script
get_template_directory_uri() .
'/js/prism.js' // location of the prism.js file
);
wp_register_script(
'ueditorconvJS', // handle name for the script
get_template_directory_uri() .
'/js/ueditorconv.js' // location of the ueditorconv.js file
);
// Enqueue the registered style and script files
wp_enqueue_style('prismCSS');
wp_enqueue_script('prismJS');
wp_enqueue_script('ueditorconvJS');
}
}
add_action('wp_enqueue_scripts', 'add_prism_scripts');参考:
