- Append the following snippet in
functions.php
which is used by current theme:
/* Load HighlightJS from CDN */
function add_highlightjs_cdn()
{
/**
* CSS:
* wp_enqueue_style( $handle, $src, $dependency, $version, $media );
* JAVASCRIPT:
* wp_enqueue_script( $handle, $src, $dependency, $version, $in_footer );
*/
wp_enqueue_style( 'highlightjs', "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/styles/default.min.css", array(), '9.15.6', 'all' );
wp_enqueue_script('highlightjs', "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/highlight.min.js", array(), '9.15.6', false);
}
add_action('wp_enqueue_scripts', 'add_highlightjs_cdn');
function load_highlightjs_script()
{
?>
<script>hljs.initHighlightingOnLoad();</script>
<?php
}
add_action('wp_footer', 'load_highlightjs_script');
- When you add code in
<code>
tag,highlightjs
will automatically highlight the code. Optionally you can add programming language specific CSS class name (e.g.swift
) in<code>
tag. Example:<pre><code class="swift"></code></pre>
(Optional) Use different styles from https://highlightjs.org/static/demo/
- As for today, Highlightjs supports 185 languages and 89 styles.
- To use any of the styles shown in https://highlightjs.org/static/demo/, change the
https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/styles/default.min.css
CSS with corresponding style. For example, if we want to change default style to Github Gist style we need to replace thedefault.min.css
withgithub-gist.min.css
. - All supported classes from CDNJS can be found in https://cdnjs.com/libraries/highlight.js.
Example of syntax highlighting in Wordpress site using HighlightJS.