How to create a folder if it doesn’t exist in WordPress theme

Post author: Adam VanBuskirk
Adam VanBuskirk
5/13/23 in

There are many reasons you may want to create a folder in a WordPress theme. One common example is some shared hosting companies when they install WordPress do not create the widely used wp-content/uploads folder. Because you cannot depend on this folder being present in freshly installed WordPress installations, if designing a theme for resale on the internet, you should do a folder check and create it if not present. Here’s how to do that using PHP.

$uploadsPath = WP_CONTENT_DIR . '/uploads';

if (!is_dir($uploadsPath)) {
    mkdir($uploadsPath, 0755, true);
    echo 'The wp-content/uploads directory was created successfully.';
} else {
    echo 'The wp-content/uploads directory already exists.';

In this example, we use the $uploadsPath variable to store the path to the wp-content/uploads directory in a WordPress installation. We then use the is_dir function to check if the directory already exists. If it doesn’t exist, we use the mkdir function to create the directory with the 0755 file permission mode (which gives read, write, and execute permissions to the owner and read and execute permissions to others).

After creating the directory, we echo a message to indicate that it was created successfully. If the directory already exists, we echo a message to indicate that it was found.

Note that the $uploadsPath variable in this example uses the WP_CONTENT_DIR constant to retrieve the path to the wp-content directory in a WordPress installation. This constant is defined in the wp-config.php file in the WordPress installation, and is typically set to something like ABSPATH . 'wp-content'.

Sign up today for our weekly newsletter about AI, SEO, and Entrepreneurship

Leave a Reply

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

Read Next

© 2024 Menyu LLC