Chap
Creating new files in the WordPress theme editor

WordPress theme editor can be used to modify theme files straight from the WordPress admin dashboard.

The editor is located under Appearance -> Editor, or in case of multi-site WordPress installation, Themes -> Editor (in the Network admin dashboard).

It is most useful for adding snippets of code, action hooks and filters to the child theme’s functions.php file, how ever, if one were to need to create a new file for the child theme, then there is no option for that. Instead you would need to manually create the file via FTP or terminal access.

As a workaround, it’s possible to add code to functions.php file that will create a new file into your desired location.

Let’s create a new file my-file.php in the child theme’s folder.

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

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

PHP
Using WordPress FileSystem API
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);
	}
});
If the functions.php file contains one or multiple namespace blocks, such as namespace Chap\Child { ... } then the code should be inserted inside of the block. If it only contains a namespace declaration, such as namespace Chap\Child; then just add the code after it.

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 never use get_template_directory(), since this would use the parent theme’s folder which would remove any custom created 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.

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