Google Code Prettify是一个用来对各种页面上的源码进行语法着色高亮显示的JavaScript库。相对于其它的代码高亮功能,Google Code Prettify很小巧,解压后也只有15K的大小。并且支持大部分常用的语言。不需要指定语言,能够自动检测代码的语言,比较智能。
- 先下载JS和CSS文件
官方地址网址:https://code.google.com/p/google-code-prettify/downloads/list
本地下载:点击下载 - 下载上面提供的JS和CSS文件放到主题目录下,并把下面的代码放到主题目录
functions.php
文件中。想改调用的路径的请自行处理…/*-----------------------------------------------------------------------------------*/ /* 代码高亮(正则匹配pre插入相应的prettify.js和css) */ /*-----------------------------------------------------------------------------------*/ add_filter('wp_footer','add_prettify'); function add_prettify(){ //定义全局post global $post; //正则匹配pre开始标签 preg_match_all('|(<pre)|i', $post->post_content, $matches); if(is_single() && !empty($matches[0])) { //如果存在pre标签时,就把以下代码加入到footer之中 ?> <link rel="stylesheet" id="is-load-css" href="<?php bloginfo('template_url'); ?>/prettify/prettify.css"/> <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/prettify/prettify.js"></script> <script type="text/javascript"> jQuery('document').ready(function(){ jQuery('.post pre').addClass('prettyprint linenums') .wrap('<div class="precode clearfix"></div>'); window.prettyPrint && prettyPrint(); }); </script> <?php } }
- 把需要着色的代码放到
<pre>
标签中即可。
另外如果你对代码着色不满意,可以去下面的网址下载你认为着色满意的CSS文件替换下载下来的即可。
评论前必须登录!
注册
社交帐号登录