Code Snippet to Create a Directory Within Uploads Folder

Here's a code snippet that allows your plugin to create a new folder in the /uploads directory on activation. Could be useful if your plugin needs to allow imports or uploads and you want them stored in a separate directory.
Our Sponsors
Essential plugins for your WooCommerce store
Build unbuildable WordPress websites
The best no-code Instagram feed plugin for WordPress

Here’s a code snippet that allows your plugin to create a new folder in the /uploads directory on activation. Could be useful if your plugin needs to allow imports or uploads and you want them stored in a separate directory.

[php]
function myplugin_activate() {

$upload = wp_upload_dir();
$upload_dir = $upload[‘basedir’];
$upload_dir = $upload_dir . ‘/mypluginfiles’;
if (! is_dir($upload_dir)) {
mkdir( $upload_dir, 0700 );
}
}

register_activation_hook( __FILE__, ‘myplugin_activate’ );
[/php]
If you enjoyed this post, make sure to subscribe to WP Mayor’s RSS feed.

Jean Galea
Jean Galea
Jean Galea is a WordPress developer, entrepreneur and padel player. He is the founder of WP Mayor, the plugins WP RSS Aggregator and EDD Bookings, as well as the Mastermind.fm podcast. His personal blog can be found at jeangalea.com.

Consider sharing this post so others can find it:

Share on facebook
Share on twitter
Share on linkedin
Share on reddit
Share on telegram
Share on whatsapp
Share on pocket
Share on email

Join thousands of people receiving real-world, genuine evaluations of WordPress products and services just like this one every week.

Table of Contents

3 Responses

  1. I prefer use the WP way than the PHP way:
    wp_mkdir_p( $upload_dir );
    or more techy:
    require_once( ABSPATH . ‘wp-admin/includes/class-wp-filesystem-base.php’ );
    require_once( ABSPATH . ‘wp-admin/includes/class-wp-filesystem-direct.php’ );
    $wp_fs_d = new WP_Filesystem_Direct( new StdClass() );
    if ( !$wp_fs_d->is_dir( $upload_dir ) && !$wp_fs_d->mkdir( $upload_dir, 0705 ) )
    wp_die( sprintf( __( ‘Impossible to create %s directory.’ ), $upload_dir ) );

    By the way, WP recommand a 705 CHMOD, not 700, and take care readers: do not use “$uploads” var name this is overwritten by WordPress.

Leave a Reply

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

The Beginner’s Handbook
From an introduction on how WordPress works to our recommendations on products and services.

Join thousands of people receiving real-world, genuine evaluations of WordPress products and services

A single weekly email directly to your inbox.