I want to store source code for blog posts within their own files. This will allow a user to download the file instead of trying to copy/paste the formatted code from within the blog post. Although I do exclude line numbers from the code, I still replace >, <, and & symbols with &gt;, &lt;, and &amp; strings to avoid these being interpreted as HTML.

I will describe how I do this by starting at the end result. Here is what this blog post contains in order to display a file with the proper formatting:

    <script>ShowDavesCodeFile( “jquerycodepre.js”, “jquerycodepre.js” );</script>

The ShowDavesCodeFile() function accepts the name of the file relative to the blog root directory. It also accepts a display name, for cases where I might need to display the name of a PHP file but actually display a text file of some sort file. PHP files will get executed if I try to let a user download them with their standard .php extension.

ShowDavesCodeFile() is stored in a file, also in the blog root directory, called jquerycodepre.js:

With that function written, I needed to add it to the WordPress JavaScript “library”. This is done by adding a few lines of code to the functions.php file in the WordPress theme directory. The lines look like this:

function include_ShowDavesCodeFile() {
	wp_enqueue_script( 'jquerycodepre', '/jquerycodepre.js' );
}

When I add a call to ShowDavesCodeFile() inline in a blog post, the script gets executed by the browser as it is creating or displaying the page. That line ends up replaced by the output of the ShowDavesCodeFile() script. It is replaced by a div and some JavaScript code that executes an AJAX call to fill the div.

The last file to write is the showcodefile.php script. This is a PHP script on the server that provides the data to go in the div. That data is <pre> and <code> element that hold the source code, as well as a paragraph and hyperlink to the source file. A look at the source for this very blog post page will show how that all looks in HTML.

And of course, that file contents:

This bit of code below is from a copy of one of the files above. I copied it to a subdirectory to make sure that a non-root path works correctly:

Note that the mechanism that I describe here is used in this post to display all of the files, except for the three lines from functions.php.

Dave