Question

I am creating a plugin in WordPress, the plugin creates logs for some events, my question is where should I write custom logs, so that no explicit file read/write permission required. I am looking to put logs at one of below two locations-
1. wp-content/plugins/pluginName/logs
2. wp-content/logs

Was it helpful?

Solution

Any files you want to create, such as logs, should be created in the wp-content/uploads/ directory. Probably in your own subdirectory. This is because this is directory will be the most reliably writable, since it needs to be writable for everyday usage (for uploading media).

You can use wp_upload_dir() to get the path to the uploads directory, and mkdir() to create a directory there:

$uploads  = wp_upload_dir( null, false );
$logs_dir = $uploads['basedir'] . '/pluginName-logs';

if ( ! is_dir( $logs_dir ) ) {
    mkdir( $logs_dir, 0755, true );
}

$file = fopen( $logs_dir . '/' . 'log.log', 'w' );

wp-content would be the next option, but I don't see any reason to prefer it over the uploads directory. Definitely don't put it inside your plugin directory. If you did you would lose any logs whenever the plugin is updated.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top