Skip to content

Instantly share code, notes, and snippets.

@arsho
Last active February 10, 2021 02:00
Show Gist options
  • Save arsho/d6c5dc49643c95ddf75ead72ac40270d to your computer and use it in GitHub Desktop.
Save arsho/d6c5dc49643c95ddf75ead72ac40270d to your computer and use it in GitHub Desktop.
Add HighlightJS syntax highlighter in Wordpress theme
  • 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 the default.min.css with github-gist.min.css.
  • All supported classes from CDNJS can be found in https://cdnjs.com/libraries/highlight.js.
@arsho
Copy link
Author

arsho commented Mar 30, 2019

highlightjs
Example of syntax highlighting in Wordpress site using HighlightJS.

@fastmarketo
Copy link

Cant highlight JS automatically detect if it is HTML, CSS, or JS?

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>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment