Display Syntax

source-codeIt is not the first concern but once you got things working, it is nice to put some of the source code on a page.

For that I use two components:

1. The WP plugin SyntaxHighlighter Evolved.   Works outstanding!

2. A (homemade) shortcode to display the contents of a source file as html, which is picked up by SyntaxHighlighter Evolved.

To do the syntax highlighting: put the code between php short codes, like:

[keyword] source code [/keyword]

in which you have to replace keyword by php.

And to display the contents of the source-file, put the following between the php-brackets:

[display_source src='functions.php startstr='display_source' endstr='end function']

The result is that a subset of ‘functions.php’ is displayed: all the source code between the strings (‘display_source’) and  ‘end function’.

/** shortcode [display_source]
Returns (part of) the contents of a source file as html.
- src      : source file in theme directory (mandatory)
             NB. use single quotes or no quotes on this argument.
             No double quotes!
- startstr : first line contains this string (optional)
- endstr   : last line contains this string (optional)

Henk Arendse, 1-dec-2013. (www.henkarendse.nl)  **/

add_shortcode( 'display_source', 'display_source_func' );

function display_source_func($atts)
	extract( shortcode_atts(
		    	'startstr' => '',
		    	'endstr' => ''),
		    'display_source' ) );

	if (empty($src)) {
		return("No source file specified");

	// read source file into $lines array
	$lines = file(html_entity_decode($src), FILE_USE_INCLUDE_PATH);

	// build $html from $lines between $start_str en $end_str
	$html = '';
	if (empty($startstr)) $start_found = true; else $start_found = false;

	foreach ($lines as $line) {
		// skip line if start string not yet found
		if (! $start_found) {
			if (strpos($line, $startstr) === false) {
			} else {
				$start_found = true;

		$html .= htmlspecialchars($line);

		// stop if end string found and displayed
		if (!empty($endstr) && strpos($line, $endstr) !== false) {

} // end function