Code Snippet to Create a Directory Within Uploads Folder

Written by Jean Galea
Written by Jean Galea
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.

Partner Sponsors

BionicWP

Full disclosure: If you purchase through a link on our site, we may earn a commission. Learn more.

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.

This article was filed in our archives.
Written by Jean Galea
Jean Galea is an investor, entrepreneur, and blogger. He is the founder of WP Mayor, the plugins WP RSS Aggregator and Spotlight, as well as the Mastermind.fm podcast. His personal blog can be found at jeangalea.com.

In this article

Discover More

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.

    1. Probably would personally stick to wp_mkdir_p() here. Using the Filesystem API would probably be a bit of overkill!

Share Your Thoughts

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

New discoveries, every week.
Join thousands of designers, developers, and builders that come to WP Mayor to find the best guides, tools, and services for their next website. One email, once a week.
WP Mayor Newsletter

Claim Your Free Website Tip 👇

Leave your name, email and website URL below to receive one actionable improvement tip tailored just for your website within the next 24 hours.

"They identified areas for improvement that we had not previously considered." - Elliot

By providing your information, you'll also be subscribing to our weekly newsletter packed with exclusive content and insights. You can unsubscribe at any time with just one click.

What's missing?