Publish: 2016-11-17 | Modify: 2017-06-21
Often friends ask me which code highlighting plugin I use for my blog. I have always used "WP-Syntax", but this plugin has a mediocre style and I don't highly recommend it. So, I will share a method to achieve code highlighting without installing a WordPress plugin, using a JavaScript plugin called highlight.js.
Usually, you would add the following code to the "header.php" file of your theme to import highlight.js and its CSS styles.
<link rel="stylesheet" href="https://libs.bsdev.cn/highlight.js/9.8.0/styles/github.css">
<script src="https://libs.bsdev.cn/highlight.js/9.8.0/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
With just the first step, you have already completed the process. Normally, when you switch to the text mode while publishing a WordPress article, you can insert the following code to achieve code highlighting.
<pre><code class="html">
Insert your code here...
</code></pre>
But typing <pre>
tags every time can be cumbersome. You can refer to the article "Enhance WordPress Editor with Code" to quickly type in specific tags. You can add the following code to the "functions.php" file in your theme directory.
// HTML text enhancement
add_action('after_wp_tiny_mce', 'bolo_after_wp_tiny_mce');
function bolo_after_wp_tiny_mce($mce_settings) {
?>
<script type="text/javascript">
QTags.addButton( 'gl', 'Code Highlighting', "\n<pre><code class=\"html\">\n\n", "</code></pre>" );
function bolo_QTnextpage_arg1() {
}
</script>
<?php
}
// HTML text enhancement ends
When publishing an article, switch to the text mode, and you will see a button for code highlighting. Double-click to type in the <pre>
tags, and then insert your code. By default, it is HTML code, so modify the <code class="html">
language according to your actual situation.
server {
listen 80;
server_name tool.xiaoz.me;
access_log /data/wwwlogs/tool.xiaoz.me_nginx.log combined;
index index.html index.htm index.php;
include /usr/local/nginx/conf/rewrite/none.conf;
root /data/wwwroot/xiaoz.me/tool;
location ~ [^/]\.php(/|$) {
#fastcgi_pass remote_php_ip:9000;
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|ico)$ {
expires 30d;
access_log off;
}
location ~ .*\.(js|css)?$ {
expires 7d;
access_log off;
}
}
highlight.js supports various code style themes. The style used above is "github.css". If you find it unattractive, you can visit the "XiaoZ Blog Front-end Library" to replace it with a style you prefer.
I come from China and I am a freelancer. I specialize in Linux operations, PHP, Golang, and front-end development. I have developed open-source projects such as Zdir, ImgURL, CCAA, and OneNav.