I’m writing a tutorial on using the R language to do some applied statistics. An example post is:

http://mcmcinirt.stat.cmu.edu/archives/223

I would like to have all of the blocks of source code be loaded from local files on the webserver. In that way, I could use git to sync them with the files that I’m actually using to develop the examples.

As it stands, I write the code on my machine, generate the graphs / check that it works, and then copy the final code into the text of the blog. This leads to duplication headaches.

Is it possible to avoid this kind of code duplication? (Either in the way I suggest or perhaps a more WordPress friendly way?)

2 Answers
2

I would not use the media uploader for this because you want to “use git to sync them with the files that I’m actually using”. There is no straightforward way to sync files uploaded via the uploader, or to update/replace those files. Core functionality in that respect is quite limited. You’d be FTPing into the server to update the files anyway and if your site stores in year/month folders just finding the files would be troublesome.

I would skip that hassle, create a directory for the R files files, and load them with a shortcode:

function srcfile_shortcode($atts="",$content="") {
  $uploads = wp_upload_dir();
  $file = $uploads['basedir'].'/rfiles/'.$atts['file'].'.r';
  if (is_readable($file)) {
    $file = file_get_contents($file);
    return '<pre>'.$file.'</pre>';
  } else {
    return 'Can not read file: '.$file;
  }
}
add_shortcode('srcfile','srcfile_shortcode');

That should load files from wp-content/uploads/rfiles with a name that matches the file shortcode attribute– that is [srcfile file="abc" /] would load wp-content/uploads/rfiles/abc.r.

You can keep the directory up to date however you like– FTP, or Git.

Tags:

Leave a Reply

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