Create a new file using the WordPress theme editor

The WordPress theme editor provides the ability to make modifications to theme files directly within the WordPress admin dashboard.

WordPress includes two native editors that enable direct editing of theme files from your browser. These are referred to as the Theme file editor and the Plugin file editor.

Where is the editor?

  • For users of Block themes, both the Theme and Plugin File Editors will be found under Tools.
  • If you’re using a Classic theme, the Theme File Editor will be located under Appearance, while the Plugin File Editor will be found under Plugins.

How do I create a new file?

If you’re using the built-in editor, you probably don’t have convenient access to the server filesystem. But the editors don’t provide a way to create new files which can be frustrating. Adding a third party plugin that provides file management is a security risk as these types of plugins are notorious for vulnerabilities. As a workaround, you can add code to your theme’s functions.php file that will generate a new file in your preferred directory.

Select the functions.php file of your currently active child theme.

Then add the following code to the file and click Update file:

Using WP FileSystem APIPHP
add_action('after_setup_theme', function() {
	$file = get_stylesheet_directory() . '/my-file.php';
	if(!file_exists($file)) {
		include_once ABSPATH . 'wp-admin/includes/file.php';
		\WP_Filesystem();
		global $wp_filesystem;
		$wp_filesystem->put_contents($file, '', FS_CHMOD_FILE);
	}
});

After adding this action, reloading any page should trigger the code and create a new file. Once the file is created most of the code will no longer execute, but should still be deleted or commented out for future use.

get_stylesheet_directory()
Refers to the current active child theme’s root directory. You should not use get_template_directory(), since this would use the parent theme’s folder which would remove any custom created files upon a theme update.

FS_CHMOD_FILE
Uses predefined permissions for the newly created file, typically 0644.

It’s also possible to create a file using PHP’s touch() function, how ever the WordPress FileSystem API should be the safer option since if that succeeds you’ll know the server is properly configured for WordPress to have filesystem access.

Using touch()PHP
add_action('after_setup_theme', function() {
	$file = get_stylesheet_directory() . '/my-file.php';
	touch($file);
});

Leave a Reply

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