The scenario

I'm developing a plugin, and part of it requires lots of text content (help descriptions) that I would prefer to keep as separate text files (in a subdirectory within the plugin) for organisational and version control purposes. The obvious candidate would be file_get_contents(), but its usage with WordPress is generally frowned upon. I've looked at some alternatives, such as wp_remote_get() (not the right one as the files are in the plugin) and the WP_Filesystem API (which seems overkill for a simple reading of text files). Is there a simple, but secure alternative? I have the nagging feeling I'm missing something very obvious.

The spec

I'm looking for a solution to:

  1. Read the contents of a HTML/text file into a variable
  2. That won't flag as insecure when used with Theme Check or similar plugins
  3. Doesn't require any writing to the files whatsoever

I had to dig pretty deep for this too, and eventually figured out some way to do this.

in my solution I used the following:

global $wp_filesystem;
$wp_filesystem->exists( '/path/to/file' ); //use any other functions available in the Filesystem API: @see https://developer.wordpress.org/reference/classes/wp_filesystem_direct/
| improve this answer | |
  • Looks promising; I'll definitely try this later this week. I originally avoided the WP_Filesystem API as it seemed more involved, but on closer inspection it looks easier than I originally thought. – Dre Jun 26 '18 at 13:11
  • Also worth noting that it is only available win the wp-admin context. It is not as easy to use in the frontend. – rfair404 Jun 27 '18 at 13:50

Put this in your plugin file:

add_action('init', 'captureFileToVariable');

function captureFileToVariable(){
    $fileName = "FileIWantToLoad.txt";
    $pluginDirectory = plugin_dir_path( __FILE__ );
    $filePath = $pluginDirectory . $fileName;
    $fileContents = file_get_contents($filePath);
| improve this answer | |
  • One of the requirements was not raising any flags. Using wp_get_contents will get you this warning: "File operations should use WP_Filesystem methods instead of direct PHP filesystem calls. Found: file_get_contents()" – NiloVelez Mar 8 '18 at 12:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.