How can I avoid code duplication for a blog with lots of source code?

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.

Leave a Comment