PHP Syntax Code Display – WordPress

What seems to be the problem from what I have had to deal with whilst making this site, is that all WordPress plugins that I have come accross have one main flaw which becomes very anoying.

All of the plugins require non standard html attributes that need to be added to the <pre> tag which when switching between the visual and html view editor they are stripped.

I did not do much searching into a solution so I just decided to look into my own solution (as usual).

The Solution

It’s not really a solution at the minute but it does solve the problem for PHP snippets and will soon figure out a better method for other languages.

There is a plugin called “MaGiKS Proper PHP Include” which is very handy for including PHP files.

I created a folder in my theme called ‘post_snippets’ and in there created a folder for each post that has snippets.

I then created a simple application for changing ‘greater than’ and ‘less than’ signs into their html entity equiverlent (you could use html entity converters but as long as those 2 are converted it doesnt matter ) by pasting the code into a textarea with clear, copy and convert buttons underneith (i will zip it up if anyone wants it) or you could use find and replace within you favorite text editor.

I then created a file within the post folder (01.php) with the converted code pasted in with the <pre> tag wrapped around.

Within the post editor simply add

[m_include_file filepath="/post_snippets/post_name/01.php"]

where you want the snippet to be displayed.

If you publish your page you’ll notice the code will be displayed nicely but without any colour.

jQuery/AJAX Syntax Plugin

I wrote this very quickly so not sure if there are any errors with it but I have had no problems.

/*
	ACT PHP Syntax Highlighter
	http://www.actwebdeigns.co.uk
	Luke Snowden
	2011
	
	$('pre').syntax({ 'url' : './syntax.php' });
*/
(function($){
    $.fn.syntax = function( options ) {
		$(this).each(function(){
			if( options.url.length != 0 ) {
				var ob = $(this);
				 $.ajax({ 
					type: 'POST', url: options.url, data: 'syntax=true&data=' + encodeURIComponent( ob.html() ), cache: false, timeout: 10000,
					error : function( html ){ alert( html ); },
					success: function(html){ ob.html( html.replace(/\t/g, '    ') ); }                            
				});
			}else{ alert( 'Please set the location of the PHP script.' ); }
		});
	};
})(jQuery);

I have created a folder in my theme called ‘syntax’ and saved the above in (php_syntax.jquery.js).

You then need to add this in the head of your theme:

// You'll need to load in  jQuery of course if not already done so
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/syntax/php_syntax.jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	$('pre').syntax({ 'url' : '<?php bloginfo('template_directory'); ?>/syntax/syntax.php' });
});

And finaly save this php script into your syntax folder (or whatever file you have defined in the option above)

<?php

if( isset( $_POST['syntax'] ) ) {
	$data = token_get_all( html_entity_decode( $_POST['data'] ) );
	$A_ff0000 = array( T_CLOSE_TAG,T_OPEN_TAG,T_LNUMBER );
	$A_006600 = array( T_ECHO,T_ELSEIF,T_ELSE,T_ARRAY,T_FOREACH,T_ISSET,T_IF,T_AS,T_REQUIRE,T_INCLUDE,T_REQUIRE_ONCE,T_EXIT,T_CLASS,T_PUBLIC,T_PRIVATE,T_STATIC,T_FUNCTION,T_RETURN,T_THROW,T_NEW );
	$A_0066ff = array( T_VARIABLE,T_PAAMAYIM_NEKUDOTAYIM );
	$A_cc0000 = array( T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE );
	$A_552200 = array( T_CONST );
	$A_0000ff = array( T_STRING,T_CONCAT_EQUAL,T_IS_EQUAL,T_IS_IDENTICAL,T_IS_NOT_EQUAL,T_IS_NOT_IDENTICAL );
	$A_ff9900 = array( T_DOC_COMMENT, T_COMMENT );
	$return = '';	
	foreach( $data as $key => $token ) {
		if( in_array( $token[0], $A_ff0000 ) ) {
			$data[$key][1] = '<span style="color:#ff0000;">' . htmlentities( $data[$key][1] ) . '</span>';
		}elseif( in_array( $token[0], $A_006600 ) ) {
			$data[$key][1] = '<span style="color:#006600;">' . htmlentities( $data[$key][1] ) . '</span>';
		}elseif( in_array( $token[0], $A_0066ff ) ) {
			$data[$key][1] = '<span style="color:#0066ff;">' . htmlentities( $data[$key][1] ) . '</span>';
		}elseif( in_array( $token[0], $A_cc0000 ) ) {
			$data[$key][1] = '<span style="color:#cc0000;">' . htmlentities( $data[$key][1] ) . '</span>';
		}elseif( in_array( $token[0], $A_552200 ) ) {
			$data[$key][1] = '<span style="color:#552200;">' . htmlentities( $data[$key][1] ) . '</span>';
		}elseif( in_array( $token[0], $A_0000ff ) ) {
			$data[$key][1] = '<span style="color:#0000ff;">' . htmlentities( $data[$key][1] ) . '</span>';
		}elseif( in_array( $token[0], $A_ff9900 ) ) {
			$data[$key][1] = '<span style="color:#ff9900;">' . htmlentities( $data[$key][1] ) . '</span>';
		}elseif( isset( $data[$key][1] ) ) {
			$data[$key][1] = htmlentities( $data[$key][1] );
		}
		$return .= ( isset( $data[$key][1] ) ? $data[$key][1] : '<span style="color:#0000ff;">' . htmlentities( $data[$key] ) . '</span>' );
	}
	echo $return;
}

?>

And that’s it, it saves space in your editor window, there’s no attribute extraction when updating or switching views, and each request per <pre> tag is around 40ms so there’s no worries there. You can see the output from the code above and if any one reading uses Dreamweaver then you’ll notice where I got the colour scheme from!

This article was written by Luke Snowden

Follow Luke Snowden on Twitter

Befriend Luke Snowden on Facebook

All context and code written within this article are the property of Luke Snowden, unless stated otherwise in which credit will be given.

This entry was posted in General. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy this password:

* Type or paste password here:

2,145 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">