wordpress-google-code-prettify

■Problem

How can I format the code by using css/js ??

I suggest You can use google-code-prettify.

最近为小站烦恼,如何修改小站的代码样式呢??虽然是老掉牙的问题,不过继续写一篇小文章记录下。方式很简单,只要加载js和css就可以了。

各种插件虽然方便,不过导致系统崩溃是经常的。。。还是Keep Simple比较好。

GIT链接

https://github.com/google/code-prettify

■WP代码

<?php
///////////
//防止代码转义 //
///////////
function g_prettify_esc_html($content)
{
 $regex = '/(<pre\s+[^>]*?class\s*?=\s*?[",\'].*?prettyprint.*?[",\'].*?>)(.*?)(<\/pre>)/sim';
 return preg_replace_callback($regex, g_prettify_esc_callback, $content);
}
function g_prettify_esc_callback($matches)
{
 $tag_open = $matches[1];
 $content = $matches[2];
 $tag_close = $matches[3];
 $content = esc_html($content);
 return $tag_open . $content . $tag_close;
}
add_filter('the_content', 'g_prettify_esc_html', 2);
add_filter('comment_text', 'g_prettify_esc_html', 2);

//////////////
//强制兼容<pre>
//把pre强制添加css样式 //
//////////////
function g_prettify_replace($text){
 $replace = array( '<pre>' => '<pre class="prettyprint linenums" >' );
 $text = str_replace(array_keys($replace), $replace, $text);
 return $text;
}
add_filter('the_content', 'g_prettify_replace');
/////////////////////
//页脚加载javascript文件 //
/////////////////////
function prettify(){

//wp_enqueue_style( 'ibmer-info-prettify-css', IBMER_PLUGIN_URL_ASSETS . '/prettify.css' );
 //加载各种自定义样式
 wp_enqueue_style( 'ibmer-info-prettify-css', IBMER_PLUGIN_URL_ASSETS . '/sons-of-obsidian.css' );
 wp_enqueue_script( 'ibmer-info-prettify-js', IBMER_PLUGIN_URL_ASSETS . '/prettify.js' );
}
add_action( 'wp_enqueue_scripts', 'prettify' );

//////////////
//加载css //
//////////////
add_action( 'wp_footer', 'ibmer_prettify_on_load_script' );
function ibmer_prettify_on_load_script()
{
 ?>
 <script type="text/javascript">
 window.onload = function(){prettyPrint();};
 </script>
 <?php 
};

//////////////
//后台编辑器添加按钮 //
//////////////
function prettify_bottom($mce_settings) {
?>
<script type="text/javascript">
QTags.addButton( 'kkpre', 'Ibmer-prettify', '<pre class="prettyprint linenums" >\n\n</pre>', "" );//添加高亮代码
QTags.addButton( 'i</>', '</>', "&lt;", "&gt;" );
function prettify_bottom() {
}
</script>
<?php
}
add_action('after_wp_tiny_mce', 'prettify_bottom');
?>

■后记

其实还可以添加界面筛选样式做的更加好,不过时间仓促,希望以后完善。